-4

我需要添加多个附件以通过 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))
4

2 回答 2

3

这是一个例子:

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

完整的代码

于 2012-06-18T06:25:14.580 回答
0

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

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

于 2012-06-18T06:16:57.920 回答