编程语言
首页 > 编程语言> > 带有附件的Python Sendmail?

带有附件的Python Sendmail?

作者:互联网

我正在用python编程.我已经有一个发送带有附件的邮件的功能,但是问题是它接收消息并将其作为附件放置.我需要它尊重消息(作为消息)和附件(作为附件).我进行了调查,发现与MIME Multipart“ MIXED”有关,但是我不知道如何在我的实际功能中添加或更改它.

这是我正在使用的函数的python代码:

def enviarCorreo(fromaddr, toaddr, file):
    msg = MIMEMultipart('mixed')
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = 'asunto'
    #adjunto
    adjunto = MIMEBase('application', "octet-stream")
    adjunto.set_payload(open(file, "rb").read())
    encode_base64(adjunto)
    adjunto.add_header('Content-Disposition', 'attachment; filename= "%s"' % file)
    msg.attach(adjunto)
    #enviar
    server = smtplib.SMTP('localhost')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddr, msg.as_string())
    server.quit()
    return

解决方法:

您忘记将文本附加为msg.attach(MIMEText(text))

def enviarCorreo(fromaddr, toaddr, text, file):
    msg = MIMEMultipart('mixed')
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = 'asunto'

    #This is the part you had missed.
    msg.attach( MIMEText(text) )

    #adjunto
    adjunto = MIMEBase('application', "octet-stream")
    adjunto.set_payload( open(file,"rb").read() )
    Encoders.encode_base64(adjunto)
    adjunto.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
    msg.attach(adjunto)

    server = smtplib.SMTP('localhost')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddr, msg.as_string())
    server.close()

enviarCorreo("x@from.com", ["y@to.com"], "Hello World", ['/tmp/sample.png'])

看看这是否适合您.

标签:mime-types,sendmail,python
来源: https://codeday.me/bug/20191202/2085476.html