下面的文件打开没有使用with语句,是不规范的。实测可用。
给出的链接是在学习过程中用到的有用的链接,代码是根据这些链接拼凑起来的。代码实现了发送邮件和附件的功能。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# http://www.runoob.com/python/python-email.html
# http://blog.csdn.net/smart55427/article/details/48783393
# http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html
#http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832745198026a685614e7462fb57dbf733cc9f3ad000
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
# 第三方 SMTP 服务
mail_host="smtp.126.com" #设置服务器
mail_user="mailnotifier@126.com" #用户名
mail_pass="xxxxxxxx" #口令
sender = 'mailnotifier@126.com'
receivers = ['aochuan103@126.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 创建带附件实例
message = MIMEMultipart()
message['From'] = 'AoChuan<mailnotifier@126.com'
message['To'] = 'Amos<aochuan103@126.com>'
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
# 正文内容
message.attach(MIMEText('Send by python & smtplib and email.\n带附件测试', 'plain', 'utf-8'))
# 构造附件1,传送当前目录下的 test.txt 文件 文件名不能出现中文名
att1 = MIMEText(open('test.caj', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="test.caj"'
message.attach(att1)
# 构造附件2,传送当前目录下的 runoob.txt 文件
att2 = MIMEText(open('test1.py', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="test1.py"'
message.attach(att2)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print "邮件发送成功"
except smtplib.SMTPException:
print "Error: 无法发送邮件"