代码如下:
参考资料为廖雪峰的Python教程http://www.runoob.com/python/python-email.html
# http://www.runoob.com/python/python-email.html
import smtplib
from email import encoders
from email.utils import parseaddr, formataddr
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
from_addr = 'crcr1994@126.com'#input('From: ')
password = 'PKM159OIJN1'#input('Password: ')
to_addr = '414481619@qq.com'#input('To: ')
smtp_server = 'smtp.126.com'#input('SMTP server: ')
mail_msg = """
<p>你好</p>
<p><a href="http://www.baidu.com">百度</a></p>
<p>图片演示:</p>
<p><img src="cid:image1"></p>
"""
msg = MIMEMultipart('related')
# msg = MIMEText('hello cr attach test...', 'plain', 'utf-8') # plain text 的msg的定义
msg['From'] = _format_addr('caorou <%s>' % from_addr)
msg['To'] = _format_addr('414481619 <%s>' % to_addr)
msg['Subject'] = Header('HELLO', 'utf-8').encode()
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
# 指定图片为当前目录
fp = open('lolita.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)
# 构造附件1,传送当前目录下的 test.txt 文件
#att1 = MIMEText(open('hello.txt', 'rb').read(), 'base64', 'utf-8')
#att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
#att1["Content-Disposition"] = 'attachment; filename="helloo.txt"'
#msg.attach(att1)
try:
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")