类名 SendEmail.py
# !/usr/bin/python
# -*- coding: UTF-8 -*-
# 遇到没有执行权限,使用 chmod a+x SendEmail.py
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from email.mime.image import MIMEImage
from email.header import Header
username = 'xxxxxxxxxxxxxxxxxxx' # 发件人邮箱账号
password = 'xxxxxxxxxxxxxxxx' # 发件人邮箱密码(授权码)
send_to = 'xxxxxxxxxxxxxxxxx' # 收件人邮箱账号,我这边发送给自己
def mail():
ret = True
msg = MIMEMultipart()
msg['From'] = formataddr(["liyang", username])
msg['To'] = formataddr(["anonymous", send_to])
subject = 'Python SMTP 邮件测试'
msg['Subject'] = Header(subject, 'utf-8')
# 正文部分
content = MIMEMultipart() # 如果仅发送一段文本,而不是html,使用 MIMEText('content','plain','utf-8') 即可
mail_msg = """
<p>Python发送复杂邮件测试...</p>
<p><a href="http://www.github.com">github仓库地址</a></p>
<p>图片演示:</p>
<p><img src="cid:image_github"></p>
"""
content.attach(MIMEText(mail_msg, 'html', 'utf-8'))
# 指定图片为当前目录
fp = open('github.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image_github>')
# markdown附件
markdown = MIMEText(open('README.md', 'rb').read(), 'base64', 'utf-8')
markdown["Content-Type"] = 'application/octet-stream'
markdown.add_header('Content-Disposition', 'attachment', filename = 'README')
# 照片附件
with open('car.png','rb') as fp:
picture = MIMEImage(fp.read())
#与txt文件设置相似
picture['Content-Type'] = 'application/octet-stream'
picture['Content-Disposition'] = 'attachment; filename = "car.png"'
# 加入到msg
msg.attach(content)
msg.attach(msgImage)
msg.attach(markdown)
msg.attach(picture)
try:
server = smtplib.SMTP_SSL("smtphz.qiye.163.com", 465) # 发件人邮箱中的SMTP服务器,网易邮箱的端口是465
server.login(username, password) # 括号中对应的是发件人邮箱账号、邮箱密码
server.sendmail(username, [send_to,], msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
server.quit() # 关闭连接
except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False
ret = False
return ret
ret = mail()
if ret:
print("邮件发送成功")
else:
print("邮件发送失败")
python3 SendEmail.py