繁体   English   中英

Python电子邮件(带有txt和html)

[英]Python email (with txt and html)

我正在尝试使用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()

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文档,看看实际发生了什么魔术。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM