-
Notifications
You must be signed in to change notification settings - Fork 0
/
py_sent_mail.py
97 lines (90 loc) · 2.78 KB
/
py_sent_mail.py
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env python
# coding=utf-8
import sys
import smtplib
from email.mime.text import MIMEText
def send(mail_info_dic):
#设置服务器所需信息
#163邮箱服务器地址
mail_host = 'smtp.163.com'
#163用户名
mail_user = 'your_email_name'
#密码(部分邮箱为授权码)
mail_pass = 'your_email_password'
#邮件发送方邮箱地址
sender = '[email protected]'
#邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
to_receivers = mail_info_dic['receivers'].split(",")
cc_receivers = mail_info_dic['Cc'].split(",") if 'Cc' in mail_info_dic else []
all_receivers = to_receivers + cc_receivers
#设置email信息
#邮件内容设置
message = MIMEText(mail_info_dic["content"],'plain','utf-8')
#邮件主题
message['Subject'] = mail_info_dic["title"]
#发送方信息
message['From'] = sender
#接受方信息
message['To'] = ";".join(to_receivers)
message['Cc'] = ";".join(cc_receivers)
#登录并发送邮件
try:
smtpObj = smtplib.SMTP()
#连接到服务器
smtpObj.connect(mail_host)
#登录到服务器
smtpObj.login(mail_user,mail_pass)
#发送
smtpObj.sendmail(sender,all_receivers,message.as_string())
#退出
smtpObj.quit()
print('success')
except smtplib.SMTPException as e:
print('error',e) #打印错误
def parser_args(argv, mail_info_dic):
'''
echo ${model_data}"/*_38" | mail -s "dssm-video: No fm_feature model data" [email protected]
python mail.py -s "mail title" [email protected],[email protected] -c [email protected],[email protected] -cont "email-content"
'''
#mail_info_dic #title、content、reciver、Cc
argv_len = len(argv)
#for i in range(argv_len-1):
i = 0
while i <= (argv_len-1):
flag = argv[i].strip()
info = ""
if i < (argv_len-1):
info = argv[i+1].strip()
if flag == "-s" and info != "":
mail_info_dic["title"] = info
i += 2
elif flag == "-c" and info != "":
mail_info_dic["Cc"] = info
i += 2
else:
mail_info_dic["receivers"] = flag
i += 1
if ("title" in mail_info_dic) and ("content" in mail_info_dic) and ("receivers" in mail_info_dic):
return True
else:
print ("Error: argv Error!")
print ('mail -s "mail title" -c [email protected],[email protected] [email protected],[email protected]')
return False
def achieve_cont_from_stdin(mail_info_dic):
content = ""
for line in sys.stdin:
if line != "":
content += line
if content != "":
mail_info_dic["content"] = content
return True
else:
print ("Error: no content!")
return False
if __name__ == '__main__':
mail_info_dic = {}
if achieve_cont_from_stdin(mail_info_dic):
if parser_args(sys.argv, mail_info_dic):
send(mail_info_dic)
else:
sys.exit(1)