记录一下自己的第一个成功的python实例,使用python代理发送邮件。
其中有三种方法,前两种是普通的文本文件发送邮件,第三种是以附件的形式发送邮件!
以下是具体的python内容:
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
|
#!/usr/bin/python
#-*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
sender = '[email protected]'
to1 = '[email protected]'
to = ["[email protected]", "[email protected]"] # 多个收件人的写法
subject = 'From Python Email test'
smtpserver = 'smtp.126.com'
username = 'wangyi'
password = '123456'
mail_postfix = '126.com'
contents = '这是一个Python的测试邮件,收到请勿回复,谢谢!!'
attachment_1 = '/tmp/test.txt'
# 第一种方法-普通文本形式的邮件
def send_mail(to_list, sub, content):
me = "Hello"+""
msg = MIMEText(content, _subtype='plain', _charset='utf-8')
msg['Subject'] = subject
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(smtpserver)
server.login(username, password)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(to, subject, contents):
print "邮件发送成功! "
else:
print "失败!!!"
# 第二种方法-普通文本形式的邮件
# msg = MIMEText('邮件内容','_subtype文件格式','字符集') 中文需参数‘utf-8’,单字节字符不需要
msg = MIMEText(contents, _subtype='plain', _charset='utf-8')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = to1
try:
smtp = smtplib.SMTP()
smtp.connect(smtpserver, 25)
smtp.login(username, password)
smtp.sendmail(sender, to1, msg.as_string())
smtp.quit()
print "发送成功!"
except:
print "失败"
# 第三种方法-发送附件
# 创建一个带附件的实例
msg = MIMEMultipart()
# 构造附件1
att1 = MIMEText(open(attachment_1, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["content-Disposition"] = 'attachment; filename="test.txt"' #这里的filename是附件的名字可以自定义
msg.attach(att1)
# 加邮件头
msg['From'] = sender
msg['To'] = to1
msg['Subject'] = subject
# 发送邮件
try:
server = smtplib.SMTP()
server.connect(smtpserver)
server.login(username, password)
server.sendmail(sender, to1, msg.as_string())
server.quit()
print "发送成功"
except:
print "失败"
|