如何将多个附件添加到电子邮件python

时间:2012-06-18 06:12:27

标签: python

我需要添加多个附件才能通过python脚本自动发送电子邮件..

我是python脚本的新手。所以请帮助。提前谢谢..

以下是代码段。

请告诉我对以下代码的更改。

themsg = MIMEMultipart()
themsg['Subject'] = Subject
themsg['To'] =','.join(Email_ID)
themsg['From'] =email_from
themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(zf_csv.read())
zf_csv.close()
msg.set_payload(zf_pdf.read())
zf_pdf.close()
Encoders.encode_base64(msg)
print 'csv attachment is'+str(os.path.basename(current_dirs+csv_to_mail))
print 'pdf attachment is'+str(os.path.basename(current_dirs+pdf_to_mail))
msg.add_header('Content-Disposition', 'attachment; filename="(%s,%s)"' %(os.path.basename(current_dirs+csv_to_mail),os.path.basename(current_dirs+pdf_to_mail))

2 个答案:

答案 0 :(得分:2)

这是一个例子:

msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = COMMASPACE.join(to_addrs_list) 
msg['Date'] = formatdate(localtime = True)
msg['Cc'] = COMMASPACE.join(cc_addrs_list)
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
msgAlternative.attach(MIMEText(content, 'plain'))

#add mutiple attachments to an Email
#attachment_paths is a list, like this:['/home/x/a.pdf', '/home/x/b.txt']
for file_path in attachment_paths:
    ctype, encoding = mimetypes.guess_type(file_path)
    if ctype is None or encoding is not None:
        ctype = dctype
    maintype, subtype = ctype.split('/', 1)
    try:
        with open(file_path, 'rb') as f:
            part = MIMEBase(maintype, subtype)
            part.set_payload(f.read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_path))
            print os.path.basename(file_path)
            msg.attach(part)
    except IOError:
         print "error: Can't open the file %s"%file_path

full code

答案 1 :(得分:0)

我不知道使用python发送邮件的方法比使用lamsonproject(lamsonproject.org)更好。

他们的API还包括向邮件添加附件 - 并且没有什么能阻止您向邮件添加多个附件。只需查看有关MailResponse及其附加方法的API。