Search code examples
pythonemailsmtplib

Python smtplib ''Subject'' why doesn't it print any subject. I've tried almost anything now


The email sending code works fine without problems, but it prints all of it in the message field. I've basically tried everything the last 3 hours. Any advice guys?

import smtplib

fromaddr="xxxxx@xxx.com"

toaddr="xxxxx@xxxx.com"

message = '''\\
         ... From: xxxxx
         ... Subject: testin'...
         ...
         ... This is a test '''

 password="xxxx"

subject="this is supposed to be the subject"

server=smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(fromaddr,password)
server.sendmail(fromaddr,toaddr,message,subject)
server.quit()
subject = "this is supposed to be the subject"

Solution

  • Creating the message using MIMEText has always worked for me. Here is how you can use it:

    import smtplib
    from email.mime.text import MIMEText
    
    # message body goes here
    message = '''\\
             ... This is a test '''
    
    msg = MIMEText(message, 'plain')
    msg['Subject'] = "this is supposed to be the subject"
    msg['From'] = "xxxxx@xxx.com"
    msg['To'] = "xxxxx@xxxx.com"
    
    server=smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(fromaddr,password)
    server.sendmail(msg['From'], msg['To'], msg.as_string())
    server.quit()
    

    I hope this helps!