使用python发送邮件

^_^的我 9月前 ⋅ 370 阅读

使用python发送邮件

使用python发送html邮件,并插入图片,附带附件,具体实现如下

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
 
# 第三方 SMTP 服务
mail_host="smtp.host.com"  #设置服务器
mail_user="account@host.com"    #用户名
mail_pass="password"   #口令 

sender = 'account@host.com'
receivers = ['405449506@qq.com', '327523057@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
 
#创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("host<account@host.com>", 'utf-8')
message['To'] =  Header("host<405449506@qq.com>", 'utf-8')
subject = '主题'
message['Subject'] = Header(subject, 'utf-8')
 
#邮件正文内容
message.attach(MIMEText('内容<p><img src="cid:image1"></p>', 'html', 'utf-8'))
 
fp = open('2.gif', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

msgImage.add_header('Content-ID', '<image1>')
message.attach(msgImage)

# 构造附件1,传送当前目录下的 1.zip 文件
att1 = MIMEText(open('1.zip', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="httpTools.zip"'
message.attach(att1)
 
# 构造附件2,传送当前目录下的 offer2.txt 文件
att2 = MIMEText(open('offer2.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="offer2.txt"'
message.attach(att2)
 
try:
    smtpObj = smtplib.SMTP() 
    smtpObj.connect(mail_host, 80)    # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)  
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "send success"
except smtplib.SMTPException:
    print "Error: failure"

全部评论: 0

    我有话说: