• [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.

  • 相关阅读:
    iOS中图片与视频一次性多选
    UIImagePickerController Class
    1月16日
    10月20日
    1月14日
    1月13日
    1月12日
    1月11日
    课程评价与建议
    加分总结
  • 原文地址:https://www.cnblogs.com/lxw0109/p/python_send_to_cc.html
Copyright © 2020-2023  润新知