Python sendmail-向MimeMultipart添加标头以避免隐藏所有收件人

时间:2018-12-06 13:47:21

标签: python python-3.x

我有一个代码,该代码发送使用HTML进行模板制作的电子邮件。 所有收件人都收到邮件,但他们都是密件抄送。

def sendMail(to, cc, bcc, template, bodyParams, subjectParams):
    global connection
    if not testCurrentConnection(connection):
        connect(currentConnectionName)
    msg = MIMEMultipart('alternative')
    subject, fromEmail, body = templateController.readTemplate(template)
    header = 'To: ' + to + '\n' + 'Cc: ' + cc + 'From: ' + fromEmail + '\n' + 'Subject: ' + subject + '\n'
    msg.attach(MIMEText(header, 'text'))
    if subjectParams:
        msg['Subject'] = templateController.replaceTextWithParams(subject, subjectParams)
    else:
        msg['Subject'] = subject
    if bodyParams:
        msg['Body'] = templateController.replaceTextWithParams(body, bodyParams)
    else:
        msg['Body'] = body

    msg['From'] = fromEmail
    msg['To'] = to
    msg['Cc'] = cc
    # no need to specify bcc here

    msg.attach(MIMEText(msg['Body'], 'html'))
    connection.sendmail(msg['From'], [msg['To'], msg['Cc'], bcc], msg.as_string())
    del msg

我正在这样调用函数:

smtpController.sendMail("myMail@gmail.com", "ccMail@gmail.com", "", "email.html", None, None)

(最后两个变量实际上是带有用于填充HTML的键-值映射关系的字典,但问题在没有它们的情况下仍然存在)

我读到我需要在邮件中添加标题以防止它,但是由于某种原因,添加标题不会改变任何内容(上述代码中的7-8行)。
我想念什么?

1 个答案:

答案 0 :(得分:0)

好的,我不知道它有什么不同,但是我通过在msg['To'] = tomsg['Cc'] = cc之前向上移动SubjectBody来解决它。我完全删除了标题。

def sendMail(to, cc, bcc, template, bodyParams, subjectParams):
    global connection
    if not testCurrentConnection(connection):
        connect(currentConnectionName)
    subject, fromEmail, body = templateController.readTemplate(template)
    msg = MIMEMultipart('alternative')
    msg['From'] = fromEmail
    msg['To'] = to
    msg['Cc'] = cc
    if subjectParams:
        msg['Subject'] = templateController.replaceTextWithParams(subject, subjectParams)
    else:
        msg['Subject'] = subject
    if bodyParams:
        msg['Body'] = templateController.replaceTextWithParams(body, bodyParams)
    else:
        msg['Body'] = body

    msg.attach(MIMEText(msg['Body'], 'html'))
    connection.sendmail(msg['From'], to.split(',') + cc.split(',') + bcc.split(','), msg.as_string())
    del msg