[Python] Send emails to the recepients specified in Message["CC"]

Recently, I'm working on a small program which needs to send emails to specific accounts. When I want

to add the function of "Copy to", I encountered a problem that the recipients specified in the Message["CC"]

CANNOT receive the emails. So I search the problem on Stack Overflow:

My code is as follows:

 from email.message import Message
 import smtplib

 def sendEmail(subject, content):
     """
     Send Email.
     """
     try:
         smtpServer = "your smtp server such as smtp.qq.com"
         userName = "liuxiaowei@mail.com"
         password = "my_passwd_is_abc"

         fromAddr = "liuxiaowei@mail.com"
         toAddrs = ["1@mail.com", "2@mail.com"]
         ccAddrs = ["3@mail.com", "4@mail.com"]

         message = Message()
         message["Subject"] = subject
         message["From"] = fromAddr
         message["To"] = ";".join(toAddrs)
         #Copy to
         #message["CC"] is only for display, to send the email we must specify it in the method "SMTP.sendmail".
         message["CC"] = "3@mail.com;4@mail.com"
         message.set_payload(content)
         message.set_charset("utf-8")
         msg = message.as_string()

         sm = smtplib.SMTP(smtpServer)
         sm.set_debuglevel(0)
         sm.ehlo()
         sm.starttls()
         sm.ehlo()
         sm.login(userName, password)

         sm.sendmail(fromAddr, toAddrs+ccAddrs, msg)
         time.sleep(5)
         sm.quit()
     except Exception, e:
         writeLog("EMAIL SENDING ERROR", "", traceback.format_exc())
     else:
         writeLog("EMAIL SENDING SUCCESS", "", "")

Note the following lines:

#message["CC"] is only for display, to send the email we must specify it in the method "SMTP.sendmail".
message["CC"] = "3@mail.com;4@mail.com"

message["CC"] is only for display. If we want to send the email to anybody, we must specify it in

the second parameter of the method "SMTP.sendmail"
:

sm.sendmail(fromAddr, toAddrs+ccAddrs, msg)

'toAddrs+ccAddrs', This is the key point.

posted @ 2015-03-18 17:46  XiaoweiLiu  阅读(367)  评论(0编辑  收藏  举报