使用Python发送带有颜色格式的电子邮件

时间:2017-06-02 07:05:46

标签: python html mime

我有以下Python代码,用于从文件filename的内容向我的ID发送电子邮件。我正在尝试使用彩色格式的文本发送电子邮件。

任何想法请指教。

def ps_Mail():
    filename = "/tmp/ps_msg"
    f = file(filename)
    if os.path.exists(filename) and os.path.getsize(filename) > 0:
        mailp = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
        msg = MIMEMultipart('alternative')
        msg['To'] = "karn@abc.com"
        msg['Subject'] = "Uhh!! Unsafe rm process Seen"
        msg['From'] = "psCheck@abc.com"
        msg1 = MIMEText(f.read(),  'text')
        msg.attach(msg1)
        mailp.communicate(msg.as_string())
ps_Mail()

1 个答案:

答案 0 :(得分:2)

以下是我用来发送HTML电子邮件的代码段。

另请阅读this

import smtplib

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

msg = MIMEMultipart('alternative')

msg['Subject'] = "Link"
msg['From'] = "my@email.com"
msg['To'] = "your@email.com"

text = "Hello World!"

html = """\
<html>
  <head></head>
  <body>
    <p style="color: red;">Hello World!</p>
  </body>
</html>
"""

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

msg.attach(part1) # text must be the first one
msg.attach(part2) # html must be the last one

s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()