如何用Python发送带有.csv附件的电子邮件
好的,我知道网上有一些问题在讨论这个,但我找不到合适的方法让它正常工作。我本以为像下面的代码这么简单就可以了,但这并没有把我的文件附加上去。任何帮助都会非常感谢。我对Python也很陌生。有没有什么邮件模块是我应该导入的,以便让这个功能正常运作呢?
import smtplib
fromaddr = "example@example.com
toaddrs = "reciever@example.com
msg = "help I cannot send an attachment to save my life"
attach = ("csvonDesktp.csv")
username = user
password = password
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg, attach)
server.quit()
2 个回答
6
在Python的官方文档里,有一个完整的示例。我可以把相关的部分复制粘贴到这里,但整个页面其实不长,所以你去那边看看会更好。
88
发送一个包含多个部分的电子邮件,并使用合适的MIME类型。
https://docs.python.org/2/library/email-examples.html
所以可能像这样(我测试过这个):
import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
emailfrom = "sender@example.com"
emailto = "destination@example.com"
fileToSend = "hi.csv"
username = "user"
password = "password"
msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = emailto
msg["Subject"] = "help I cannot send an attachment to save my life"
msg.preamble = "help I cannot send an attachment to save my life"
ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
if maintype == "text":
fp = open(fileToSend)
# Note: we should handle calculating the charset
attachment = MIMEText(fp.read(), _subtype=subtype)
fp.close()
elif maintype == "image":
fp = open(fileToSend, "rb")
attachment = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == "audio":
fp = open(fileToSend, "rb")
attachment = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(fileToSend, "rb")
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
msg.attach(attachment)
server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login(username,password)
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()