【问题标题】:Why email is not being send to CC list?为什么电子邮件没有发送到抄送列表?
【发布时间】:2019-07-03 02:38:00
【问题描述】:

我有以下代码,其中Cc 电子邮件列表不起作用,这意味着电子邮件收到Cc 列表中的人员/组,To 列表中的电子邮件正在工作,我就是不知道出了什么问题?关于如何调试和修复它的任何指导?

import time,smtplib
import pprint,logging,os,time,json
from subprocess import Popen, PIPE, call
from pprint import pprint
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase

email = 'username2@company.com'
gerriturl = ""

def sendEmail2(type,data):
    global originalchange
    global gerriturl,email,username1
    body = '''%s''' % (data)
    #msg = MIMEMultipart(body)
    msg = MIMEMultipart()
    sender = 'techci@company.com'
    receivers = []
    cc = ['username1@company.com']
    REPLY_TO_ADDRESS = 'embedded-tech-integrators@group.company.com'
    if type =='failure':
        print("Inside  failure email %s"%email)
        b = '\U0001F6A8'
        print("b.decode('unicode-escape')")
        receivers.append('username2@company.com')
        #receivers.append(email)
        print('%s'%receivers)
        msg['Subject'] = '%s AUTO  FAILED FOR GERRIT %s :PLEASE TAKE IMMEDIATE ACTION!!!'%(b.decode('unicode-escape'),gerriturl)
    msg['From'] = sender
    msg['To'] = ', '.join(receivers)
    msg['Cc'] = ', '.join(cc)
    msg["Content-Type"] = "text/html"
    try:
        mail = smtplib.SMTP('relay.company.com', 25)
        msg.attach(MIMEText(body, 'html'))
        msg.add_header('reply-to', REPLY_TO_ADDRESS)
        print('Email sent successfully %s %s'%(receivers,cc))
    except Exception as e:
        logger.error('Problem sending email')
        logger.error('%s' % e)
def main():
    data = "THIS IS A TEST EMAIL"
    sendEmail2('failure',data)

if __name__ == "__main__":
    main()

【问题讨论】:

标签: python smtp


【解决方案1】:

重要的是要将收件人电子邮件地址的完整列表传递给 sendmail() 方法 - 您需要将 ToCCBCC 字段的电子邮件地址连接到一个列表中,而不是一个字符串。

import smtplib

def send_email(subject, body_text, emails_to, emails_cc=[], emails_bcc=[]):
    # Configuration
    host = "localhost"
    port = 1025
    from_addr = "nobody@somewhere.com"
    # Build the email body
    body = "\r\n".join([
            "From: %s" % from_addr,
            "To: %s" % ', '.join(emails_to),
            "CC: %s" % ', '.join(emails_cc),
            "Subject: %s" % subject ,
            "",
            body_text
            ])
    # Prepare the complete list of recipient emails for the message envelope
    emails = emails_to + emails_cc + emails_bcc
    # Connect to the server
    server = smtplib.SMTP(host, port)
    # Send the email
    server.sendmail(from_addr, emails, body)
    # Close the server connection
    server.quit()

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 2012-03-20
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 2015-05-03
    相关资源
    最近更新 更多