使用带主题的SMTP发送python电子邮件

时间:2015-02-27 00:01:28

标签: python email smtp bcc subject

我正在尝试使用SMTP在Python中发送电子邮件,包括发件人地址,收件人地址,BCC地址,主题和邮件。我有电子邮件发送,它甚至发送到BCC,唯一的问题是电子邮件的消息说:

To: example@gmail.com

Subject: Subject goes here

this is the email that I’m sending

当我只希望消息本身显示消息所在的位置,并且未设置电子邮件的主题时,所以有一个空白的主题。以下是我设置的方法:

def sendEmail(fromAddress, toAddress, bccAddress, appName, message):

    subject = "Subject goes here"
    BODY = string.join((
            "From: %s\r\n" % fromAddress,
            "To: %s\r\n" % toAddress,
            "Subject: %s\r\n" % subject,
            "\r\n",
            message
            ), "\r\n")

    #im using arbitrary values here, when I run it I use actual login info
    username = 'example@gmail.com'
    password = 'password'
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login(username,password)

    toList = []
    bccList = []
    toList.append(toAddress)
    bccList.append(bccAddress)
    server.sendmail(fromAddress, toList + bccList, BODY)
    server.quit()

1 个答案:

答案 0 :(得分:0)

使用email包(docs)。

from email.mime.text import MIMEText

def send_mail(to, from_addr, subject, text):
    msg = MIMEText(text)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to
    s = smtplib.SMTP_SSL("smtp.gmail.com")
    s.login(smtp_user, smtp_pass)
    # for Python 3
    s.send_message(msg)
    # OR
    # for Python 2 (or 3, will still work)
    s.sendmail(from_addr, [to], msg.as_string())
    s.quit()