0

I am trying to send an email in Python using SMTP, with a From address, To address, BCC address, subject, and message. I have the email sending, and it even sends to the BCC as it should, the only issue is that the message of the email says:

To: example@gmail.com

Subject: Subject goes here

this is the email that I’m sending

when I only want the message itself to show where the message belongs, and the subject of the email isn't set, so there's a blank subject. Here is how I have it set up:

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()
AggieDev
  • 5,015
  • 9
  • 26
  • 48

1 Answers1

0

Use the email package (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()
Tom Hunt
  • 916
  • 7
  • 21