使用python发送电子邮件

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
37
38
39
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/12/7 上午9:40
# @Author : Dwk
# @File : send_email.py
# smtplib 负责邮件的发送
# email负责邮件的内容
import smtplib
from email.mime.text import MIMEText

# 邮件服务器配置
mail_host = "smtp.gmail.com"
mail_user = "XXX"
mail_pass = "XXXXXX"
sender = "XXXXXXX"
# 可接受多个发送地址
receivers = ["XXXXXX"]

# 邮件内容
# text/html是指以html网页形式发送的,而text/plain是以纯文本格式发送的
message = MIMEText('content', 'plant', 'utf-8')
# 邮件主题
message['Subject'] = 'title'
# 发送方
message['From'] = sender
# 接受方
message['To'] = receivers[0]

# 登录并发送
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj = smtplib.SMTP_SSL(mail_host, 465)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print('success')
except smtplib.SMTPException as e:
print('error', e)

下面这个例子是添加了附件的

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/12/7 上午9:40
# @Author : Dwk
# @File : send_email.py
# smtplib 负责邮件的发送
# email负责邮件的内容
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage


# 邮件服务器配置
mail_host = "smtp.gmail.com"
mail_user = "dwk715"
mail_pass = "XXXXX"
sender = "dwk715@gmail.com"
# 可接受多个发送地址
receivers = ["dwk715@hotmail.com"]

# 邮件内容
# text/html是指以html网页形式发送的,而text/plain是以纯文本格式发送的
# 邮件主题
message = MIMEMultipart()
message['Subject'] = '测试'
# 发送方
message['From'] = sender
# 接受方
message['To'] = receivers[0]
# 使用HTML的正文内容
with open('content.html', 'r') as f:
content = f.read()
part1 = MIMEText(content, 'html', 'utf-8')
# 添加附件
with open('addone.txt', 'r') as add:
content2 = add.read()
part2 = MIMEText(content2, 'plain', 'utf-8')
# 设置内容类型,为二进制流
part2['Content-Type'] = 'application/octet-stream'
# 设置附件,添加文件名
part2['Content-Disposition'] = 'attachment;filename="addone.txt"'
# 添加照片附件,注意此处是rb读取方式
with open('01.jpg', 'rb') as f_image:
image = MIMEImage(f_image.read())
# 设置内容类型,为二进制流
image['Content-Type'] = 'application/octet-stream'
# 设置附件,添加文件名
image['Content-Disposition'] = 'attachment;filename="01.jpg"'
# 添加内容到邮件主体中
message.attach(part1)
message.attach(part2)
message.attach(image)


# 登录并发送
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj = smtplib.SMTP_SSL(mail_host, 465)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print('success')
except smtplib.SMTPException as e:
print('error', e)