Home > Software engineering >  Python email sending
Python email sending

Time:10-13

I have a small code to send an email within python. However, I would like to separately define the message Subject and message main body. The 'sendmail function" however does not accept "subject" input. Please advise. Tnx

host = "smtp.gmail.com"
port = 465
sender_email = "*****@gmail.com"
password = "****"
receiver_email = "****@gmail.com"
subject = "Test email"
message = "Hello World"

try:
  smtp_ssl = smtplib.SMTP_SSL(host, port)
except Exception as e:
  smtp_ssl = None

resp_code, response = smtp_ssl.login(sender_email, password)                     
smtp_ssl.sendmail(from_addr = sender_email, to_addrs = receiver_email, msg = message)  
resp_code, response = smtp_ssl.quit()

CodePudding user response:

change

message = "Hello World"

to:

subject = "My subject"
body = "Hello World"
message = f"Subject: {subject}\n\n{body}"

Good luck.

CodePudding user response:

Thanks Arturas. Now It works fine.

  • Related