python发邮件

使用自动发送邮件功能,添加附件(图片,文件等)

# hanbb
# come on!!!
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
import os

# 基础信息构建
msg_from = '填发送的邮箱'    # 发送方邮箱
passwd = '填密码'           # 填入发送方邮箱的授权码(密码)
msg_to = '填收件的邮箱'      # 收件人邮箱

# 邮件对象
msg = MIMEMultipart()
msg['From'] = Header('程序小冰')   # 收件显示的标题
msg['To'] = Header(msg_to)

subject = "python邮件测试"         # 主题
msg['Subject'] = Header(subject,'utf-8')

### 邮件中添加链接 和 图片
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.csindex.com.cn/">中证指数</a></p>
<p>图片演示:</p>
<p><img src="cid:image1"></p>
"""
msg.attach(MIMEText(mail_msg, 'html', 'utf-8'))

# 指定图片为当前目录
fp = open("C:\\Users\\HBB\\Desktop\\中证1208.png", 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)
###

# 邮件正文是MIMEText:
content = "这是程序小冰使用python程序发送的文件"
msg.attach(MIMEText(content, 'plain', 'utf-8'))

# 首先是xlsx类型的附件
xlsxpath = 'C:\\Users\\HBB\\Desktop\\质量分数.xlsx'
xlsxpart = MIMEApplication(open(xlsxpath, 'rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename='{}'.format(os.path.basename(xlsxpath)))
msg.attach(xlsxpart)

# jpg类型的附件
jpgpath = 'C:\\Users\\HBB\\Desktop\\mayi.png'
jpgpart = MIMEApplication(open(jpgpath, 'rb').read())
jpgpart.add_header('Content-Disposition', 'attachment', filename='{}'.format(os.path.basename(jpgpath)))
msg.attach(jpgpart)

# mp3类型的附件
# mp3part = MIMEApplication(open('kenny.mp3', 'rb').read())
# mp3part.add_header('Content-Disposition', 'attachment', filename='benny.mp3')
# msg.attach(mp3part)

# pdf类型附件
# part = MIMEApplication(open('foo.pdf', 'rb').read())
# part.add_header('Content-Disposition', 'attachment', filename="foo.pdf")
# msg.attach(part)

try:
    s = smtplib.SMTP_SSL("smtp.163.com", 465)
    s.login(msg_from, passwd)
    s.sendmail(msg_from, msg_to, msg.as_string())
    print("发送成功")

except smtplib.SMTPException:
    print("发送失败")

finally:
    s.quit()

 参看文件:

https://www.cnblogs.com/yufeihlf/p/5726619.html

http://www.runoob.com/python/python-email.html

posted @ 2017-12-19 21:09  hbb360  阅读(182)  评论(0编辑  收藏  举报