Python:使用smtplib模块发送邮件时“主题”未显示
我已经成功地使用smtplib模块发送电子邮件了。但是,当我发送邮件时,发出去的邮件里没有主题。
import smtplib
SERVER = <localhost>
FROM = <from-address>
TO = [<to-addres>]
SUBJECT = "Hello!"
message = "Test"
TEXT = "This message was sent with Python's smtplib."
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
我应该怎么写“server.sendmail”才能把主题也包含在发送的邮件里呢?
如果我用server.sendmail(FROM, TO, message, SUBJECT),就会出现“smtplib.SMTPSenderRefused”的错误。
10 个回答
19
试试这个:
import smtplib
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['From'] = 'sender_address'
msg['To'] = 'reciver_address'
msg['Subject'] = 'your_subject'
server = smtplib.SMTP('localhost')
server.sendmail('from_addr','to_addr',msg.as_string())
45
这段代码可以在使用Gmail和Python 3.6及以上版本时正常运行,它使用了一个新的“EmailMessage”对象:
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg.set_content('This is my message')
msg['Subject'] = 'Subject'
msg['From'] = "me@gmail.com"
msg['To'] = "you@gmail.com"
# Send the message via our own SMTP server.
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("me@gmail.com", "password")
server.send_message(msg)
server.quit()
212
把它作为一个头部添加:
message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
然后:
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
还可以考虑使用标准的Python模块 email
- 这个模块在写邮件的时候会对你帮助很大。使用它的方式如下:
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = TO
msg.set_content(TEXT)
server.send_message(msg)