发送电子邮件包括主题字段,使用Python SMTP

时间:2017-06-27 09:38:42

标签: python smtp gmail

我使用server.sendmail(fromaddr, toaddrs, msg)使用python发送自动电子邮件。

如何添加邮件主题的电子邮件? 我试图查看SMTP文档,但没有找到任何相关文档。

1 个答案:

答案 0 :(得分:2)

来自How to send an email with Gmail as provider using Python?

def send_email(user, pwd, recipient, subject, body):
import smtplib

gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body

# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.login(gmail_user, gmail_pwd)
    server.sendmail(FROM, TO, message)
    server.close()
    print 'successfully sent the mail'
except:
    print "failed to send mail"