之前一直使用linux的sendEmail来自动发送邮件,但是阿里云上,禁止使用25端口发送邮件,必须使用加密协议,如587端口,sendEmail的软件最后一版是2009年,试了下,很难兼容CentOS7,所以就想到用python来实现。自己网上搜罗了下稍加修改,再加上自己加了批量发送多个目标邮件地址的功能,代码如下:
#C:\Python27# -*- coding: utf-8 -*-
import os,re
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr,formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import smtplib
from_user = 'opm@xxx.cn'
password = 'dfffE9xVDtPkdz'
smtp_server = 'smtp.exmail.qq.com'
smtp_port = 587
maindir = '/home/appadm/open***-2.4.4/user'
confdir = '/home/appadm/open***-2.4.4/'
file1 = os.path.join(maindir,'open***-install-2.4.4-I601.exe') #附件1,一个安装程序,路径/home/appadm/open***-2.4.4/user/open***-install-2.4.4-I601.exe
file2 = os.path.join(maindir,'open***-readme.docx') #附件2,安装操作手册,路径'/home/appadm/open***-2.4.4/open***-readme.docx
mail_list = [] 目标邮件组初始为空,该mail_list为变量,与下面的‘mail_list’不同
flist = open('mail_list','r') 本地目录下有一个mail_list的文件,收件人全部写进去,每行一个收件人
for line in flist.readlines():
mail_list.append(line.strip())
def sendmail():
###以下到邮件正文前的代码可以忽略,由于我的附件3要取邮箱的前缀作为用户名,举例,xwz@qq.com,我的附件3是xwz.tar.gz,另外要到psw-file这个文件中账号xwz以及对应的密码
for to_user in mail_list:
suser = to_user.strip().split("@")[0]
fpath = os.path.join(maindir,suser)
ftar = suser + '.tar.gz'
file3 = os.path.join(fpath,ftar)
userm = suser + '.+'
os.chdir(confdir)
os.chdir('config')
sd = os.getcwd()
f = open('psw-file','r')
for line in f.readlines():
m = re.search(userm,line)
if m is not None:
userinfo = m.group()
f.close()
useracc = userinfo.split()[0]
userpass = userinfo.split()[1]
#############以下为邮件正文######
mail_content = '''Hello,your open*** account is: %s,
and your password is: %s''' % (useracc,userpass)
###############
msg = MIMEMultipart() 带附件的邮件
msg['From'] = from_user 发件人
msg['To'] = to_user 收件人
msg['Subject'] = Header(u"测试环境: %s\'s open*** imformation" % suser).encode() 标题
mail_text = MIMEText(mail_content,'plain','utf-8') 内容格式
msg.attach(mail_text) 正文内容
exepart = MIMEApplication(open(file1, 'rb').read()) 附件1
exepart.add_header('Content-Disposition', 'attachment', filename='open***-install-2.4.4-I601.exe')
msg.attach(exepart)
docpart = MIMEApplication(open(file2, 'rb').read()) 附件2
docpart.add_header('Content-Disposition', 'attachment', filename='open***-readme.docx')
msg.attach(docpart)
tarpart = MIMEApplication(open(file3, 'rb').read()) 附件3
tarpart.add_header('Content-Disposition', 'attachment', filename=ftar)
msg.attach(tarpart)
server = smtplib.SMTP(smtp_server,smtp_port) smtp服务器以及端口
server.starttls()
#server.set_debuglevel(1)
server.login(from_user,password) 发件人账号密码
server.sendmail(from_user,to_user,msg.as_string()) 发送格式
server.quit()
if __name__ == '__main__':
print "Mail sending......."
sendmail()
print "Mail processed Over"
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。