python标准库之邮件

python标准库中的smtplib模块对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
37
38
39
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
import smtplib

class quickmail:
def __init__(self, from_addr=None, password=None, nickname='系统邮件', server_ip='smtp.163.com'):
# 普通的邮件发送
# self.server = smtplib.SMTP()
# self.server.connect(server_ip, port=25)

# 加密的邮件发送, 数据在传输过程中会被加密。
self.server = smtplib.SMTP_SSL()
self.server.connect(server_ip, port=465)

self.from_addr = from_addr
self.nickname = nickname
self.server.login(self.from_addr, password)

def write_mail(self, content=None, title='测试邮件', content_type='plain'):
# 'plain'表示无格式的纯文本内容, 'html'表示网页格式的内容
self.mimetext = MIMEText(content, content_type, 'utf-8')
self.mimetext['Subject'] = Header(title, 'utf-8').encode()
self.mimetext['From'] = formataddr((Header(self.nickname, 'utf-8').encode(), self.from_addr))

def send_mail(self, to_addrs):
self.mimetext['To'] = ",".join(to_addrs)

# 发送邮件
self.server.sendmail(from_addr, to_addrs, self.mimetext.as_string())
self.server.quit()

if __name__ == '__main__':
from_addr = 'xxxxxx@163.com'
password = 'xxxxxx' # 对于163邮箱来说需要输入的是授权码

mail = quickmail(from_addr=from_addr, password=password)
mail.write_mail('这是一封测试邮件', '试试邮件发送')
mail.send_mail(['123456@qq.com','123456@163.com'])
0%