通过SMTP发送附件时,正文/文本为空

时间:2019-04-24 12:02:49

标签: python python-3.x smtp smtplib

如果有使用smtplib的附件,我将无法通过电子邮件发送任何文本或html正文。如果没有通过附件,则正文可见/不为空。

我尝试使用MIMEMultipart('alternative'),将文本发送为msg.attach(MIMEText(kwargs.get('text'), 'plain')),将正文发送为msg.attach(MIMEText(body)),并将附件发送为msg.attach(MIMEApplication(fil.read(),Content_Disposition='attachment; filename="%s"' % basename(f),Name=basename(f)))

代码如下-

    msg = MIMEMultipart('alternative')
    author = formataddr((str(Header(header)), sender))
    msg['From'] = author
    msg['To'] = ','.join(receiver)
    msg['Subject'] = subject

    if "reply_to" in kwargs and kwargs["reply_to"]:
        msg['Reply-to'] = kwargs["reply_to"]

    if 'Bcc' in kwargs:
        if not isinstance(kwargs['Bcc'], list):
            kwargs['Bcc'] = [kwargs['Bcc']]
        receiver = receiver + kwargs['Bcc']
        msg['Bcc'] = ','.join(kwargs['Bcc'])

    if 'Cc' in kwargs:
        if not isinstance(kwargs['Cc'], list):
            kwargs['Cc'] = [kwargs['Cc']]
        receiver = receiver + kwargs['Cc']
        msg['Cc'] = ','.join(kwargs['Cc'])

    if 'text' in kwargs:
        msg.attach(MIMEText(kwargs.get('text'), 'plain'))

    if body != []:
        if 'mime_only' in kwargs and kwargs['mime_only']:
            msg.attach(MIMEText(body))
        else:
            msg.attach(MIMEText(body, 'html'))

    if 'files' in kwargs:
        files = kwargs['files']
        for f in files:
            with open(f, "rb") as fil:
                msg.attach(MIMEApplication(
                    fil.read(),
                    Content_Disposition='attachment; filename="%s"' % basename(f),
                    Name=basename(f)
                ))

所有部分都可以单独工作,即-我能够发送文本电子邮件,html电子邮件和附件,但不能发送HTML或带有附件的文本。

我注意到的一件事是,当我收到gmail邮件时,它确实在单击邮件之前(在通知/摘要中)显示了正文内容,但是当我单击或打开它时,正文不存在。

0 个答案:

没有答案