Greg
Greg

Reputation: 19

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'] = "[email protected]"
msg['To'] = '[email protected]'
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('[email protected]', 'password1')
server.sendmail(msg['From'], msg['To'], msg['Subject'])
server.quit()

screenshot of the inbox

Upvotes: 0

Views: 1212

Answers (1)

tripleee
tripleee

Reputation: 189607

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'] = "[email protected]"
msg['To'] = '[email protected]'
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('[email protected]', 'password1')
    server.send_message(msg)
    server.quit()

Upvotes: 2

Related Questions