带有文本正文和文件附件的Python SMTP

时间:2015-06-25 22:31:39

标签: python smtp

我正在尝试打开一个文本文件并以纯文本形式将其邮寄到正文中,我还需要将其他几个日志文件附加到电子邮件中。

import smtplib
from email.MIMEText import MIMEText 
from email.MIMEMessage import MIMEMessage

recipient = 'people@people.com'

def mail (recipient, ):

        fp = open('data.txt', 'r')
        msg = MIMEText(fp.read())
        fp.close()
        me = "jeff@noname.com"
        msg['Subject'] =  "Test Results" 
        msg['From'] = me
        msg['To'] = recipient
        s = smtplib.SMTP('localhost')
        s.sendmail(me, recipient.split(), msg.as_string())
        s.quit()

mail (recipient, )

这将打开data.txt文件,并将所有内容放入电子邮件正文中。这是我想要的,我需要保持这个。但我还想在电子邮件中添加4-6个附件并保留正文。任何人都有任何提示可以帮助解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

看看这是否适合你 -

import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
    assert type(send_to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    fp = open('data.txt', 'r')
    msg.attach(MIMEText(fp.read()))
    fp.close()

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(f, "rb").read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

send_mail() # don't forget to provide the required parameters here before executing the code