0

I've written a very basic script in Python that allows me to send emails more quickly/easily. I don't really intend to use it day to day, it's more a proof of concept for myself.

I can't get the subject line to appear though. I can send emails but when I try to include the subject line with the method I describe at the bottom of this question it just doesn't send the email (I'm aware the subject is currently commented out!). Here is my code currently:

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 to the send mail line like this:

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

But it didn't do anything.

I hope this isn't a really stupid question. I'm only starting out teaching myself Python.

Benno
  • 51
  • 1
  • 3
  • 7

3 Answers3

1

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.

BIU
  • 2,340
  • 3
  • 17
  • 23
1

You can a attach it as a header:

msg = 'Subject: %s\n%s' % (subject_text, message_text)

server = smtplib.SMTP(SERVER)
server.sendmail(fromaddress, toaddress, msg)
server.quit()

You should consider using standard Python module email - it will help you a lot while composing emails.

Tom
  • 1,105
  • 8
  • 17
1

See specify-a-sender-when-sending-mail..., the subject is a mime header.

You can utilize the email.message.Message class, and use it to generate mime headers, including from:, to: and subject.

Send the as_string() result using smtplib (see other answers).

>>> from email import message
>>> m1=message.Message()
>>> m1.add_header('from','me@no.where')
>>> m1.add_header('to','myself@some.where')
>>> m1.add_header('subject','test')
>>> m1.set_payload('test\n')
>>> m1.as_string()
'from: me@no.where\nto: myself@some.where\nsubject: test\n\ntest\n'
>>>
Community
  • 1
  • 1
gimel
  • 83,368
  • 10
  • 76
  • 104