Search code examples
pythonemailmime

Sending email with Python, the msg["Subject"] variable doesn't behave as it should


I'm sending emails with Python, but the msg["Subject"] variable populates the body of the email instead of the subject box, and the variable body, populates nothing...

Everything else works fine, but I can't figure out why the subject is the body and the body is empty? What have I missed?

Here's the code:

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

msg = MIMEMultipart()
msg['From'] = "myemail@gmail.com"
msg['To'] = 'anemail@hotmail.com'
msg['Subject'] = "for next delivery, please supply"

body = Merged_Dp_Ind_str
msg.attach(MIMEText(body, 'plain'))

text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('username@gmail.com', 'password1')
server.sendmail(msg['From'], msg['To'], msg['Subject'])
server.quit()

screenshot of the inbox


Solution

  • Your message is fine, but you are not actually sending it; you are only sending the Subject.

    server.sendmail(msg['From'], msg['To'], msg['Subject'])
    

    You apparently mean

    server.sendmail(msg['From'], msg['To'], text)
    

    However, you should probably update your code to use the modern Python 3.6+ APIs instead.

    The proper modern way to format and send the message is something like

    import smtplib
    from email.message import EmailMessage
    
    msg = EmailMessage()
    msg['From'] = "myemail@gmail.com"
    msg['To'] = 'anemail@hotmail.com'
    msg['Subject'] = "for next delivery, please supply"
    msg.set_content(Merged_Dp_Ind_str)
    
    with smtplib.SMTP('smtp.gmail.com', 587) as server:
        server.starttls()
        server.login('username@gmail.com', 'password1')
        server.send_message(msg)
        server.quit()