您好,登錄后才能下訂單哦!
之前一直使用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。