首页 > 解决方案 > 为什么电子邮件没有发送到抄送列表?

问题描述

我有以下代码,其中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()

标签: pythonsmtp

解决方案


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

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()

推荐阅读