Search code examples
pythonsmtpgmailsmtplib

Populate other email fields like Subject in Python mail function


I have tested this piece of code and it sends the email successfully, it tends to leave the subject fields, cc and bcc fields empty as seen in the photo.

import smtplib

gmail_user = 'dummy@gmail.com'  
gmail_password = 'password'



sent_from = 'dummy@gmail.com'  
to = ['receiver@gmail.com']  
subject = 'OMG Super Important Message'  
body = "Hey, what's up?\n\n- You"

email_text = """\
From: %s  
To: %s  
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

try:  
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    print("establish connection successful")
    server.ehlo()
    print("identification successful")
    server.login(gmail_user, gmail_password)
    print("login successful")
    server.sendmail(sent_from, to, email_text)
    print("send mail successful")
    server.close()
    print('Email sent!')
except:  
    print('Something went wrong...')

Does anyone know how I can fill them up through this script?

Screenshot of received mail


Solution

  • For the email subject - there is a specific format to the input arg you provide to server.sendmail that should work. Could you try:

    subject = 'This is the email subject'
    text = 'This is the email body'
    message = "Subject: {}\n\n{}".format(subject, text)
    server.sendmail(sender, recipient, message)