【问题标题】:Attach a txt file in Python smtplib在 Python smtplib 中附加一个 txt 文件
【发布时间】:2012-03-21 11:02:57
【问题描述】:

我正在发送如下纯文本电子邮件:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_message():
    msg = MIMEMultipart('alternative')
    s = smtplib.SMTP('smtp.sendgrid.net', 587)
    s.login(USERNAME, PASSWORD)

    toEmail, fromEmail = to@email.com, from@email.com
    msg['Subject'] = 'subject'
    msg['From'] = fromEmail
    body = 'This is the message'

    content = MIMEText(body, 'plain')
    msg.attach(content)
    s.sendmail(fromEmail, toEmail, msg.as_string())

除了这条消息,我想附上一个 txt 文件,“log_file.txt”。如何在此处附加 txt 文件?

【问题讨论】:

    标签: python email smtp


    【解决方案1】:

    同样的方式,使用msg.attach:

    from email.mime.text import MIMEText
    
    filename = "text.txt"
    f = file(filename)
    attachment = MIMEText(f.read())
    attachment.add_header('Content-Disposition', 'attachment', filename=filename)           
    msg.attach(attachment)
    

    【讨论】:

    • 作为旁注,我必须在附件之后附加内容,否则正文中的纯文本没有显示。
    • email.mime.text 适合我,但 email.MIMEText 不适合
    【解决方案2】:

    对我有用

    sender = 'spider@fromdomain.com'
    receivers = 'who'
    
    msg = MIMEMultipart()
    msg['Subject'] = 'subject'
    msg['From'] = 'spider man'
    msg['To'] = 'who@gmail.com'
    file='myfile.xls'
    
    msg.attach(MIMEText("Labour"))
    attachment = MIMEBase('application', 'octet-stream')
    attachment.set_payload(open(file, 'rb').read())
    encoders.encode_base64(attachment)
    attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
    msg.attach(attachment)
    
    print('Send email.')
    conn.sendmail(sender, receivers, msg.as_string())
    conn.close()
    

    【讨论】:

      【解决方案3】:

      从 Python3.6 开始,我建议开始使用 EmailMessage 而不是 MimeMultipart。更少的导入,更少的行,无需将收件人都放在邮件头和 SMTP 发件人函数参数中。

      import smtplib
      from email.message import EmailMessage
      
      msg = EmailMessage()
      msg["From"] = FROM_EMAIL
      msg["Subject"] = "Subject"
      msg["To"] = TO_EMAIL
      msg.set_content("This is the message body")
      msg.add_attachment(open(filename, "r").read(), filename="log_file.txt")
      
      s = smtplib.SMTP('smtp.sendgrid.net', 587)
      s.login(USERNAME, PASSWORD)
      s.send_message(msg)
      

      更好的是通过pip3 install envelope 安装库envelope,其目的是以非常直观的方式处理许多事情:

      from envelope import Envelope
      from pathlib import Path
      
      Envelope()\
          .from_(FROM_EMAIL)\
          .subject("Subject")\
          .to("to")\
          .message("message")\
          .attach(Path(filename))\
          .smtp("smtp.sendgrid.net", 587, USERNAME, PASSWORD)\
          .send()
      

      【讨论】:

        猜你喜欢
        • 2021-11-15
        • 2015-02-21
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        • 2019-10-23
        • 2020-02-21
        相关资源
        最近更新 更多