代码
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# 第三方 SMTP 服务
mail_host="smtp.exmail.qq.com" # 设置服务器
mail_user="xiaqu@qq.com" # 用户名
mail_pass="password" # 密码
sender = 'xiaqu@qq.com' # 发件人
receivers = ['xiaqu@qq.com'] # 收件人
message = MIMEMultipart()
message['From'] = Header("发件人名称", 'utf-8') # 可以填发件人的人名或邮箱地址
message['To'] = Header("收件人名称", 'utf-8') # 可以填收件人的人名或邮箱地址
subject = '博客备份 %s' % time.strftime("%Y-%m-%d") # 标题
message['Subject'] = Header(subject, 'utf-8')
#邮件正文内容
message.attach(MIMEText('Hi, 博客备份文件见附件,请查收!', 'plain', 'utf-8'))
# 构造附件1
att1 = MIMEText(open('typecho-mysql.sql.gz', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中的附件就显示什么名字
att1["Content-Disposition"] = 'attachment; filename="typecho-mysql.sql.gz"'
message.attach(att1)
# 构造附件2
att2 = MIMEText(open('typecho-html.tar', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中的附件就显示什么名字
att2["Content-Disposition"] = 'attachment; filename="typecho-html.tar"'
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: 无法发送邮件"
本文链接:
http://blog.ps-ef.cn/Python/29.html