Search code examples
python-2.7smtplib

Recepients are in BCC field when sending email


Whenever I run my code the recipients are in the bcc field rather than the To field (When I check my gmail inbox)

I have no idea what can be the reason. How can I stop the recipients being in the BCC field. and make them appear in the TO field Here is my code

import smtplib 
import getpass
import time
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

smtpVar = smtplib.SMTP ("smtp.gmail.com", 587)
fromEmail = "myemail@gmail.com"
toEmails = ["myemail@gmail.com", "secondemail@gmail.com"]

msgVar = MIMEMultipart()
msgVar ["From"] = fromEmail
msgVar ["To"] = toEmails

# I am getting the contents of the body of the email from a text file
fileOpen1 = open ("EmailBody.txt", "r")
msgBody = MIMEText (fileOpen1.read())
fileOpen1.close()

smtpVar.ehlo()
smtpVar.starttls()

passwordVar = getpass.getpass (prompt="Enter Password  : ")
smtpVar.login ("myemail@gmail.com", passwordVar)

smtpVar.sendmail (msgVar ["From"], msgVar ["To"] , "Subject: Test Email-.......[Email Date/Time] " + time.strftime("%Y" + "-" + "%m" + "-" + "%d" + "_" + "%H" + ":" + "%M" + ":" + "%S") + "\n" + msgBody.as_string())

smtpVar.quit()
print ("\n\n.....message sent successfully!!!\n\n")

Solution

  • smtplib doesn't create the message headers for you. The from and to arguments are just used for the envelope. If you want them to appear in the header, you have to do that yourself.

    smtpVar.sendmail (msgVar ["From"], msgVar ["To"] , "From: " + msgVar["From"] + "\nTo: " + msgVar["To"].join(", ") + "\nSubject: Test Email-.......[Email Date/Time] " + time.strftime("%Y-%m-%d_%H:%M:%S") + "\n" + msgBody.as_string())