import smtplib
import ssl
message = f"""\
Subject: this is a email
this is a message.
"""
smtp_server="yoursmtpserver"
port = 465
sender_email="youremail"
receiver_email="receiver email"
password = "your password"
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.encode("utf-8"))
发现报错:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 18-19: ordinal not in range(128)
解决办法:
修改context
context = ssl._create_unverified_context()
修改后的代码:
import smtplib
import ssl
message = f"""\
Subject: this is a email
this is a message.
"""
smtp_server="yoursmtpserver"
port = 465
sender_email="youremail"
receiver_email="receiver email"
password = "your password"
# context = ssl.create_default_context()
context = ssl._create_unverified_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.encode("utf-8"))