【问题标题】:Python email (with txt and html)Python 电子邮件(带 txt 和 html)
【发布时间】:2016-02-10 21:58:09
【问题描述】:

我正在尝试使用 html 和 txt 发送和发送电子邮件。但我需要将 .txt 文件的内容放入电子邮件 html 正文中。到目前为止,我只能让 txt 文件或 html 文件工作,但不能同时工作。有什么想法吗?

import smtplib

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

sender = "sender@gmail.com"
receiver = "receiver@gmail.com"

msg = MIMEMultipart('alternative')
msg['Subject'] = "update"
msg['From'] = sender
msg['To'] = receiver

f1 = (open("email_data.txt"))
text = MIMEText(f1.read(),'plain') 

html = """\
<html>
  <head></head>
  Header
  <body>
    <p>Something<br>
       Update<br>
       Need the contents of the text file to open here
    </p>
  </body>
</html>
"""


#part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(text)
msg.attach(part2)


server = smtplib.SMTP('smtp.gmail.com', 587)

server.starttls()
server.ehlo()
server.login("sender", "password")
server.sendmail(sender, receiver, msg.as_string())
print 'Email sent'
server.quit()

【问题讨论】:

    标签: python email smtplib


    【解决方案1】:

    yagmail 的绝佳案例。

    import yagmail
    yag = yagmail.SMTP('username','password')
    
    html = '<h1>some header text</h1><p>{}</p>'.format(f1.read())
    
    yag.send('toaddr@gmail.com', 'subject', html)
    

    完成。

    最好阅读上面链接中的 yagmail 文档,看看实际发生了什么。

    【讨论】:

    • 不客气,很高兴它成功了。欢迎在 github 上接受答案或点赞 :-)
    【解决方案2】:

    我认为您正在寻找字符串格式,最基本的用例是

    """the text i want to insert is the following {} """.format(text)
    

    【讨论】:

    • 我要插入的文本是一个大文件,每次我运行以电子邮件作为最终输出的脚本时都会发生变化,所以我总是会有不同的文本。
    猜你喜欢
    • 2021-09-15
    • 1970-01-01
    • 2011-12-30
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多