如何使用Python发送带有.csv附件的电子邮件[重复]

发布于 2021-01-29 15:06:31

这个问题已经在这里有了答案

在Python smtplib中附加txt文件 (3个答案)

6年前关闭。

好的,我知道这里有一些问题可以解决,但是我找不到找到使其正常工作的方法。我认为它和下面的代码一样简单,但这不会附加我的文件。任何帮助将不胜感激。我对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()
关注者
0
被浏览
72
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    发送包含适当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()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看