-1

my friend and I have been coding an email sender, but we can't send a subject with the email if you could help; much appreciated:

import smtplib

def send_email(send_to, subject, message):
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)

    server.login("*******", "******")

    server.sendmail('******', send_to, message, subject)

    server.quit()

target = input('Who are you sending the email to? ')
subj = input('What is your subject? ')
body = input('Enter the message you want to send: ')

send_email(target, subj, body)

except SMTPException:
   print("Error: unable to send email")
FlatBoulders
  • 75
  • 2
  • 3
  • 14

1 Answers1

1

The call to smtplib.SMTP.sendmail() does not take a subject parameter. See the doc for instructions on how to call it.

Subject lines, along with all other headers, are included as part of the message in a format called RFC822 format, after the now-obsolete document that originally defined the format. Make your message conform to that format, like so:

import smtplib fromx = 'xxx@gmail.com' to = 'xxx@gmail.com' subject = 'subject' #Line that causes trouble msg = 'Subject:{}\n\nexample'.format(subject) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.ehlo() server.login('xxx@gmail.com', 'xxx') server.sendmail(fromx, to, msg) server.quit()

Of course, the easier way to conform your message to all appropriate standards is to use the Python email.message standard library, like so:

import smtplib from email.mime.text import MIMEText fromx = 'xxx@gmail.com' to = 'xxx@gmail.com' msg = MIMEText('example') msg['Subject'] = 'subject' msg['From'] = fromx msg['To'] = to server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.ehlo() server.login('xxx@gmail.com', 'xxx') server.sendmail(fromx, to, msg.as_string()) server.quit()

Other examples are also available.