|
python之用smtplib模块使用第三方smtp发送邮件(通过flask实现一个http接口)
1、邮件发送
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
| #!/usr/bin/env python
#coding:utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def email_send(recipient,theme,message,path=None,filenames=None):
local_hostname = ['toby-ThinkPad-T430shhhh']
msg = MIMEMultipart('related')
#第三方smtp服务器
smtp_server = 'mxxx.xxxxp.com'
mail_user = 'xxxxxx@xxxx.com'
mail_pass = 'xxxxxx'
#发件人和收件人
sender = 'xxxxxx' #发件人
receiver = recipient#收件人
msg['Subject'] = theme #邮件主题
#纯文本格式内容
#text = MIMEText('这是纯文本内容', 'plain', 'utf-8')
#msg.attach(text)
#html内容
html_msg = '''
<html><head><body>
<p>%s</p>
</body></head></html>
''' % message
html = MIMEText(html_msg,'html','utf-8')
msg.attach(html)
#构造附件
if path == None and filenames == None:
pass
else:
files = path + filenames
att = MIMEText(open(files, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename=%s' % filenames
msg.attach(att)
#发送邮件
try:
smtp = smtplib.SMTP()
smtp.connect(smtp_server)
smtp.ehlo(local_hostname) #使用ehlo指令向smtp服务器确认身份
smtp.starttls() #smtp连接传输加密
smtp.login(mail_user, mail_pass)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
return True
except smtplib.SMTPException,ex:
print ex
'''
if __name__ == "__main__":
#接口格式: 收件人、主题、消息,[路径,附件]
theme = '这是一封测试邮件'
message = '测试邮件,请查阅,谢谢!'
to_mail = ['xxxxxx@urundp.com','xxxx9@qq.com','xxxxx4@139.com']
if email_send(to_mail,theme,message) == True:
print '邮件发送成功'
else:
print '邮件发送失败'
'''
|
2、flask
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| #!/usr/bin/env python
#_*_ coding:utf-8 _*_
from flask import Flask, request
from mail import email_send
app = Flask(__name__)
@app.route('/')
def index():
email = request.args.get('email')
data = email.split(',')
if email_send(data[0],data[1],data[2],data[3]=None,data[4]=None) == True:
print '邮件发送成功'
else:
print '邮件发送失败'
return '<h1>%s</h1>' % email
if __name__ == "__main__":
app.run(debug=True)
#发送格式 http://127.0.0.1:5000/?email=xxxxx@qq.com,emailsub,message
|
|
|