-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSendMail.py
More file actions
78 lines (66 loc) · 2.29 KB
/
Copy pathSendMail.py
File metadata and controls
78 lines (66 loc) · 2.29 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
# -*- coding: utf-8 -*-
# MUA: Mail User Agent
# MTA: Mail Transfer Agent
# MDA: Mail Delivery Agent
# 发件人 -> MUA -> MTA -> MTA -> 若干个MTA -> MDA <- MUA <- 收件人
########### msn.com info ###############
# 服务器名称: pop-mail.outlook.com
# 端口: 995
# 加密方法: TLS
#
# 服务器名称: imap-mail.outlook.com
# 端口: 993
# 加密方法: TLS
#
#
# 服务器名称: smtp-mail.outlook.com
# 端口: 587
# 加密方法: STARTTLS
from email import encoders
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
def sendMail():
import pickle
mailInfoPath = r'D:\temp\python_mail_info.txt'
#############################################
# write mail info to local file
# with open(mailInfoPath, 'wb') as f:
# info = {'from' : '[email protected]',
# 'password' : 'xxxxxxxxx',
# 'to' : '[email protected]',
# 'smtp server' : 'xxxxxxxxx',
# 'smtp port' : 'xxxx'}
# f.write(pickle.dumps(info))
#############################################
import os
if (not os.path.exists(mailInfoPath)):
print('FAIL TO SEND MAIL. mail info file does not exist: %s' % mailInfoPath)
return
info = None
with open(mailInfoPath, 'rb') as f:
info = pickle.load(f)
print(info)
# construct mail message
msg = MIMEText(
'hello, send by python', # text
'plain', # subtype
'utf-8')
msg['From'] = _format_addr('JingweiPythonTester <%s>' % info['from'])
msg['Subject'] = Header('Test email sent from python by Jingwei', 'utf-8').encode()
import smtplib
print('smtplib.SMTP(). Connecting to (%s, %s)' % (info['smtp server'], info['smtp port']))
server = smtplib.SMTP(info['smtp server'], int(info['smtp port']))
print('smtplib.SMTP(). Connected')
server.set_debuglevel(1)
server.ehlo()
server.starttls()
print('server.login()...')
server.login(info['from'], info['password'])
print('server.sendmail()...')
server.sendmail(info['from'], [info['to']], msg.as_string())
print('server.sendmail() done')
server.quit()