|
普通邮件
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
| [iyunv@localhost checksalt]# cat python_email.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
def smtp(title,file):
import smtplib
from email.mime.text import MIMEText
from email.header import Header
with open(file, 'r') as f:
content = f.read()
#加邮件头
msg=MIMEText(content,'plain', 'utf-8')
to_list=['XXX1@qq.com',XXX2@qq.com]
msg['from'] = 'XXX@qq.com'
msg['subject'] = title
#发送邮件
try:
server = smtplib.SMTP()
server.connect('smtp.exmail.qq.com')
server.login('XXX@qq.com','xxxxx')#XXX为用户名,xxxxx为密码
server.sendmail(msg['from'],to_list,msg.as_string())
server.quit()
print '发送成功'
except Exception, e:
print str(e)
if __name__ == '__main__':
smtp(sys.argv[1],sys.argv[2])
[iyunv@localhost checksalt]#
|
带附件邮件
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
| #!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
oneday = datetime.timedelta(days=1)
today = datetime.date.today()
yesterday = datetime.date.today() - oneday
yesterday_time = datetime.datetime.strftime(yesterday, '%Y-%m-%d')
sender = 'xxxx_xxxx@xxxx.com' ##发送者
receivers = ['xxxx@xxxx.com','xxxx@xxxx.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
#创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("来源", 'utf-8')
message['To'] = Header("目的", 'utf-8')
subject = 'xxxx日志'
message['Subject'] = Header(subject, 'utf-8')
#邮件正文内容
message.attach(MIMEText('%sxxxx日志信息,请看附件!!'% yesterday_time, 'plain', 'utf-8'))
# 构造附件,传送当前目录下的 test.txt 文件
try:
file = 'file.log.%s' % yesterday_time
print file
att1 = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = "attachment; filename=extProfile.log.%s" %yesterday_time
message.attach(att1)
smtpObj = smtplib.SMTP()
smtpObj.connect('smtp.exmail.qq.com')
smtpObj.login('xxxx_xxxx@xxxx.com', 'xxxxxxxxxxxx') # XXX为用户名,XXXXX为密码
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print "邮件发送成功"
except smtplib.SMTPException as e :
print str(e)
print "Error: 无法发送邮件"
except IOError as e:
print str(e)
print "Error: 无法发送邮件"
|
|
|
|