Search code examples
pythonemailmime

Emails are not getting trigerred to CC recipients


I have developed a python code to send mails to the selected users. Mails are getting delivered to "TO" recipients but not to "CC" recipients.

There can be 100s of CC recipients and those information will be hardcoded.

Please help me in identifying the mistake here in the below code

conn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=Birthday_Database.accdb;')
cur = conn.cursor()
sql = ("SELECT Name,DOB,Image,Email FROM Calendar where DOB = {}".format(t2))
cur.execute(sql)
df = cur.fetchall()    

if len(df) == 0:
    print("There are no Birthday's for today!!!!")
    sys.exit(0)

for row in df:
    myVar1 = row.Name
    myVar2 = row.Image
    myVar3 = row.Email

# Define these once; use them twice!
    strFrom = 'do.not.reply@abc.com'
    strTo = myVar3
    Image = myVar2
    Names = myVar1
    strcc = ['qwerty@abc.com','ytrewq@abc.com','poiuyt@abc.com']
    strcc = ','.join(strcc)

    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'Happy Birthday {0}'.format(Names)
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo
    msgRoot['Cc'] = strcc
    #msgRoot['Cc'] = strcc
    msgRoot.preamble = 'This is a multi-part message in MIME format.'
    print(msgRoot['Cc'])
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    msgText = MIMEText('This is the alternative plain text message.')
    msgAlternative.attach(msgText)

    msgText = MIMEText('<br><img src="cid:image1">', 'html')
    msgAlternative.attach(msgText)

    fp = open("Images\{0}".format(Image),"rb")
    msgImage = MIMEImage(fp.read())
    fp.close()

    msgImage.add_header('Content-ID', '<image1>')
    msgRoot.attach(msgImage)

    import smtplib
    smtp = smtplib.SMTP()
    smtp.connect('outlook.abc.com')
    #smtp.login('exampleuser', 'examplepass')

    smtp.sendmail(strFrom,strTo+strcc, msgRoot.as_string())
    smtp.quit()

Solution

  • According to the docs:

    Send mail. The required arguments are an RFC 822 from-address string, a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address), and a message string.

    According to that, your concatenated string is going to be treated as a single address. To fix it, create a list and use it for the to_addrs parameter.

    to_addrs = [strTo] + cc_list
    

    where cc_list is strcc in as a list.