我正在尝试使用Python电子邮件客户端发送电子邮件。我编写了以下代码,但它将attachemnt作为正文发送,而不是附加文件。
有人可以告诉我代码有什么问题:
# Import smtplib for the actual sending function
import smtplib
# Here are the email package modules we'll need
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
EMAIL_LIST = ['rec@rec.com']
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'THIS DOES NOT WORK'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = 'send@sender.com'
print EMAIL_LIST
print '--------------------'
print ', '.join(EMAIL_LIST)
msg['To'] = ', '.join(EMAIL_LIST)
msg.preamble = 'THIS DOES NOT WORK'
fileName = 'c:\\p.trf'
with open(fileName, 'r') as fp:
attachment = MIMEText(fp.read())
fp.close()
msg.add_header('Content-Disposition', 'attachment', filename=fileName)
msg.attach(attachment)
# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail('julka@pv.com', EMAIL_LIST, msg.as_string())
s.quit()
答案 0 :(得分:0)
对于附件,您应该使用MIMEBase
这样的内容:
import os
from email import encoders
from email.mime.base import MIMEBase
with open(fileName,'r') as fp:
attachment = MIMEBase('application','octet-stream')
attachment.set_payload(fp.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition','attachment',filename=os.path.split(fileName)[1])
msg.attach(attachment)