pythonemailsmtplibsubject

How do I add a subject line to emails?


In my script in Python to send emails I can't get the subject line to appear. I can send emails but when I include the subject line it doesn't send the email (I'm aware the subject is commented out):

import smtplib


candidate_name = raw_input("Candidate Name: ")
candidate_email = raw_input("Candidate Email: ")

# Specifying the from and to addresses
fromaddr = 'XXXX'
toaddrs  = '%s' % candidate_email
#subject = 'Phone call'

# Writing the message (this message will appear in the email)
msg = '''
Hi %s

Thanks for taking my call just now. As discussed if you could send me a copy of your CV        that would be great and I'll be back in touch shortly.

Cheers
XXXX''' %candidate_name

username = 'XXXX'
password = 'XXXX'

# Sending the mail
server = smtplib.SMTP('XXXX')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
print "Email sent to %s at %s" % (candidate_name, candidate_email)
server.quit()

I tried adding subject:

server.sendmail(fromaddr, toaddrs, subject, msg)

But it didn't do anything.


Solution

  • Declaration of SMTP.sendmail:

    SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

    It expects the subject as part of the message, and the message to be the third argument passed. You're moving the message to the fourth argument and sending it and the subject separately.