Python SMTP发送带附件的邮件

今天研究了一下使用Python发送带附件的邮件,我选择了使用qq邮箱SMTP来发送。

模块如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#coding=utf-8
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib, datetime

msg = MIMEMultipart()

def alarmMail(receriver,picname):
#Mail server conf
mail_sender = 'robot@eliyar.biz'
mail_sender_password = 'automail917'
SMTP_server = 'smtp.exmail.qq.com'
server = smtplib.SMTP(SMTP_server)
server.login(mail_sender,mail_sender_password)

#mail setting
msg['to'] = receriver
msg['from'] = mail_sender
msg['subject'] = Header('ALARM: Invader Detected (' + str(datetime.date.today()) + ')','gb2312')

#mail body
body_txt = MIMEText('Some one invaded the house, please cheak up the attachments')
msg.attach(body_txt)

#Add four attachment
for i in range(1,5):
att = MIMEText(open('imgs/%s_%i.jpg' %(picname,i) , 'rb').read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="%s_%i.jpg"'%(picname,i)
msg.attach(att)

#Send mail
server.sendmail(msg['from'], msg['to'], msg.as_string())
server.close()
print('Successfully send mail to %s' %receriver)

搞成函数模式是为了在另一个py文件中调用,我设定了两个变量收件人mailto和图片名字picname。使用方法是先导入函数

1
2
3

from mail import alarmMail

然后引用函数

1
2
3

alarmMail('eliyar917@foxmail.com','pictest')

参考