1、邮件发送 mailsend.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
|
#_*_ coding:utf-8 _*_
import
smtplib
from
email.mime.multipart
import
MIMEMultipart
from
email.mime.text
import
MIMEText
class
Sendmail:
local_hostname
=
[
'xxxx'
]
msg
=
MIMEMultipart(
'related'
)
def
__init__(
self
,smtp_server,mail_user,mail_pass):
self
.smtp_server
=
smtp_server
self
.mail_user
=
mail_user
self
.mail_pass
=
mail_pass
def
mess(
self
,theme,message):
Sendmail.msg[
'Subject'
]
=
theme
# 邮件主题
html_msg
=
'''
<html><head><body>
<p>%s</p>
</body></head></html>
'''
%
message
html
=
MIMEText(html_msg,
'html'
,
'utf-8'
)
Sendmail.msg.attach(html)
def
files(
self
,path
=
None
,filenames
=
None
):
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
Sendmail.msg.attach(att)
def
send(
self
,receiver):
smtp
=
smtplib.SMTP()
smtp.connect(
self
.smtp_server)
smtp.ehlo(
self
.local_hostname)
# 使用ehlo指令向smtp服务器确认身份
smtp.starttls()
# smtp连接传输加密
smtp.login(
self
.mail_user,
self
.mail_pass)
smtp.sendmail(
self
.mail_user, receiver, Sendmail.msg.as_string())
smtp.quit()
if
__name__
=
=
"__main__"
:
pass
|
2、python flask web框架实现一个http接口
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
|
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
from
flask
import
Flask,request
import
json
from
mailsend
import
Sendmail
app
=
Flask(__name__)
@app
.route(
'/sendmail'
, methods
=
[
'GET'
,
'POST'
])
def
index():
if
request.method
=
=
'POST'
:
jsondata
=
request.get_data()
data
=
json.loads(jsondata)
s,e,f,r
=
data[
'smtpserver'
],data[
'emailsubject'
],data[
'filepath'
],data[
'receivesuser'
]
email
=
Sendmail(s[
'server'
],s[
'mailuser'
],s[
'mailpasswd'
])
email.mess(e[
'subject'
],e[
'mess'
])
email.files(f[
'path'
],f[
'files'
])
print
'邮件正在发送...'
email.send(r[
'receiver'
])
return
'邮件发送成功'
else
:
return
'<h1>只接受post请求!</h1>'
if
__name__
=
=
'__main__'
:
app.run(debug
=
True
,host
=
'0.0.0.0'
)
|
3、调用这个接口发送邮件(不管是什么语言调用这个http接口,只要是传送json数据格式即可)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#_*_ coding:utf-8 _*_
#POST方式发送邮件数据到smtp http转发接口
import
urllib2
import
json
def
http_post():
url
=
'http://192.168.89.8:5000/sendmail'
data
=
{
'smtpserver'
: {
'server'
:
'mail.xxxxx.com'
,
'mailuser'
:
'txxtixnrxn@xrxdp.com'
,
'mailpasswd'
:
'1qaz#EDC'
},
'emailsubject'
: {
'subject'
:
'这次测试做的很晚'
,
'mess'
:
'现在好困'
},
'filepath'
: {
'path'
:
'/etc/'
,
'files'
:
'passwd'
},
'receivesuser'
: {
'receiver'
:
'23456723@qq.com'
}}
headers
=
{
'Content-Type'
:
'application/json'
}
req
=
urllib2.Request(url
=
url, headers
=
headers, data
=
json.dumps(data))
response
=
urllib2.urlopen(req)
return
response.read()
resp
=
http_post()
print
resp
|
本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/1874915