python - 發送html格式的郵件


import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header

# 設置smtplib所需的參數
# 下面的發件人,收件人是用於郵件傳輸的。
smtpserver = 'smtp.126.com'
username = 'xiauxue0687@126.com'
password = '**********'
sender = 'xiaoxue0687@126.com'
# receiver='XXX@126.com'
# 收件人為多個收件人
receiver = ['526886905@qq.com']

subject = 'Python email test'
# 通過Header對象編碼的文本,包含utf-8編碼信息和Base64編碼信息。以下中文名測試ok
# subject = '中文標題'
# subject=Header(subject, 'utf-8').encode()

# 構造郵件對象MIMEMultipart對象
# 下面的主題,發件人,收件人,日期是顯示在郵件頁面上的。
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = 'xiaoxue0687@126.com <xiaoxue0687@126.com>'
# msg['To'] = 'XXX@126.com'
# 收件人為多個收件人,通過join將列表轉換為以;為間隔的字符串
msg['To'] = ";".join(receiver)
# msg['Date']='2012-3-16'

# 構造文字內容
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"
text_plain = MIMEText(text, 'plain', 'utf-8')
msg.attach(text_plain)

# 構造圖片鏈接
sendimagefile = open(r'F:\RobotTest\testimage.png', 'rb').read()
image = MIMEImage(sendimagefile)
image.add_header('Content-ID', '<image1>')
image["Content-Disposition"] = 'attachment; filename="testimage.png"'
msg.attach(image)

# 構造html
# 發送正文中的圖片:由於包含未被許可的信息,網易郵箱定義為垃圾郵件,報554 DT:SPM <p><img src="cid:image1"></p>
html = """
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.baidu.com">link</a> you wanted.<br>
</p>
</body>
</html>
"""
text_html = MIMEText(html, 'html', 'utf-8')
text_html["Content-Disposition"] = 'attachment; filename="texthtml.html"'
msg.attach(text_html)

# 構造附件
sendfile = open(r'F:\RobotTest\1111.txt', 'rb').read()
text_att = MIMEText(sendfile, 'base64', 'utf-8')
text_att["Content-Type"] = 'application/octet-stream'
# 以下附件可以重命名成aaa.txt
# text_att["Content-Disposition"] = 'attachment; filename="aaa.txt"'
# 另一種實現方式
text_att.add_header('Content-Disposition', 'attachment', filename='aaa.txt')
# 以下中文測試不ok
# text_att["Content-Disposition"] = u'attachment; filename="中文附件.txt"'.decode('utf-8')
msg.attach(text_att)

# 發送郵件
smtp = smtplib.SMTP()
smtp.connect('smtp.126.com')
# 我們用set_debuglevel(1)就可以打印出和SMTP服務器交互的所有信息。
# smtp.set_debuglevel(1)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM