Search code examples
pythonsmtpsmtplib

smtplib subject not showing, encoded subject in message


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

def emailSender(emailId, password, input):
    fromaddr = emailId
    emailFile = open(input, "r")  # open the generated email file with read only access
    msgTxt = ""
    server = smtplib.SMTP('outbound.___.com')
    server.starttls()
    server.login(fromaddr, password)
    for line in emailFile:
        if line.__contains__("$to$"):
            toaddr = line[4:]
        elif line.__contains__("$cc$"):
            cc = line[4:]
        elif line.__contains__("$bcc$"):
            bcc = line[5:]
        elif line.__contains__("$subj$"):
            subject = line[6:]
        elif line.__contains__("$%$"):
            msg = MIMEMultipart()
            msg['From'] = fromaddr
            msg['To'] = toaddr
            subject = subject.encode('utf-8')
            msg['Subject'] = "hello world"
            msg['Cc'] = cc
            msg.attach(MIMEText(msgTxt, 'plain'))
            text = msg.as_string()
            server.sendmail(fromaddr, toaddr, text)
            msgTxt = ""
        elif not line.__contains__("--------------------------------------------------------------------"):
            msgTxt += line

    server.quit()


if __name__ == '__main__':
    password = "****"
    emailId = "****"
    input = "input"

    emailSender(emailId, password, input)

Overall goal is to take a text file with to email, cc, subject and message and send that email and do this for several generated emails in the text file.

I am reading email from a text file which is msgTxt. I also take the subject, toaddr & cc from the text file. It sends the email fine with the to and from showing but it does not show the subject of the email. I have tried debugging smtplib and ssl files but can't seem to figure out. When debugging, the msg has all of the attributes properly set but doesn't get transferred to the email. Any help is much appreciated. I've been stuck on this for some time now. Thank you for the help in advanced.

--Bijan


Solution

  • I'm going out on a limb here, but:

            msg['From'] = fromaddr
            msg['To'] = toaddr
            msg['Subject'] = "hello world"
    

    ..."fromaddr" comes from the code, not the file. So, "subject" is the first key you define after the first key you define that comes from the text file.

    Suppose that the text lines in the file have the wrong line terminator, and this gets appended to toaddr. Then From works, because it's hardcoded. Also To works, because the line terminator has not occurred yet. It occurs immediately after To.

    Here you leave two line terminator-equivalents, so SMTP stops processing the headers and the subject is now considered part of the message body.

    To verify, try hard-coding the "To" addr for once. If it works, you need to trim() the lines you get from your file.