Python带附件的群发邮件脚本

本文介绍如何使用Python的smtplib和email模块发送包含HTML表格的邮件,包括邮件的基本设置、HTML数据的创建与附加、附件的发送及SMTP服务器的配置。

所用系统windows7,python版本3.4.2,如果是2.x的话需要将print()修改为print

# -*- coding: utf-8 -*-
import smtplib,sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

User = 'ak_neo101@163.com'
Pwd  = 'Avr96.'
To   = ['ak_neo102@163.com','1265921100@qq.com','ak_neo102@sina.com']
SMTP = 'smtp.163.com'

msg = MIMEMultipart()
msg['Subject'] = 'Python Test' #邮件标题
msg['From'] = User             #发件人 
msg['To'] = To[0]              #收件人


#发送HTML数据
HTML = MIMEText("""
HTML表格部分
<table border="1">
  <tr>
    <th>第一行</th>
    <th>元素1</th>
    <th>元素2</th>
  </tr>
  <tr>
    <th>第二行</th>
    <th>元素1</th>
    <th>元素2</th>
  </tr>
</table>
HTML文字
""",'html','utf-8')
msg.attach(HTML)

#发送文字部分,当与HTML一块发送时这部分会当做附件,可以考虑在html中嵌入文字
#Text = MIMEText('Python2.x-3.x测试文字')
#msg.attach(Text)

#发送附件
#try:
#    bina = MIMEApplication(open('test.xlsx','rb').read())
#    bina.add_header('Content-Disposition', 'attachment', filename="test.xlsx")
#    msg.attach(bina)
#except Exception:
#    print('Open File Error!')
#    sys.exit()


try:
    server = smtplib.SMTP(SMTP,port=25,timeout=15)
except Exception:
    print('SMTP Address Error!')
    sys.exit()

#开启TLS安全传输,非必须
try:
    server.starttls
except Exception:
    print('Start TLS Error!')
    sys.exit()

try:
    server.login(User,Pwd)
except Exception:
    print('Login Error!' )
    sys.exit()

ToList = len(To)
for i in range(ToList):
    try:
        server.sendmail(User,To[i],msg.as_string())
    except Exception:
        print('Send  Mail Error! The address is',To[i])
        continue
    print('Send SUCCESSFUL!')
server.quit()



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值