- 邮件内容,及收件人都放在一个txt文件中。读取该文件。这样也方便维护内容。
- 检查指定文件夹中是否有附件存在。
- 通过账户及密码登录outlook邮箱服务器,然后发送。
- 这里面应该还可以扩展下,例如整合某些自动处理的表格,然后发送邮件。
import smtplib
from email.mime.text import MIMEText #MIMEText:内容形式为纯文本、超文本(html)。
from email.header import Header
from email.mime.multipart import MIMEMultipart #MIMEMultupart:多形式组合,可包含文本、图片、附件。
from email.mime.application import MIMEApplication
import sys,os
def mailcontent(): #读取自定义txt文件的内容
receiver_List=[]
content_List=[]
all_content=[]
#filename=os.path.join(sys.path[0],"Mail_Content.txt") #Mail_Content文件需要在程序同一个文件路径下面
filename="D:\\My Documents\\SendMail\\Mail_Content.txt"
f=open(filename,'r')
for line in f:
all_content.append(line.rstrip("\n"))
receiver_List=all_content[(all_content.index("Mail Address:")+1):(all_content.index("Mail Subject:"))]
subject_List=all_content[all_content.index("Mail Subject:")+1]
content_List=all_content[(all_content.index("Mail Content:")+1):]
my_receiver=[i for i in receiver_List if i!=""]
my_content=[i for i in content_List if i!=""]
return my_receiver,subject_List,my_content
def CheckAtt(): #检查有没有附件
#print(sys.path[0]) #获取当前程序的工作目录
allfile=[] #定义一个空列表
#Attlink=os.path.join(sys.path[0],"Attachment")
Attlink="D:\\My Documents\\SendMail\\Attachment"
for name in os.listdir(Attlink): #获取该目录下的文件列表
if name!="":
filelink=os.path.join(Attlink,name) #构造包含附件名的绝对路径
allfile.append(filelink)
return allfile
def sendmail(receiver, subject, content, att):
msg_from='your mail account' #发送方邮箱
passwd='your mail password' #填入发送方邮箱的授权码/登录密码
msg_to=receiver #收件人邮箱
msg=MIMEMultipart() #创建一个多对象组合
msg.attach(MIMEText(content,'plain','utf-8')) #粘贴文件内容到邮件对象中
if att!="": #如果附件列表不为空
for file in att: #遍历每个附件
attachfile=MIMEApplication(open(file,'rb').read()) #读取一个附件对象
attachfile.add_header('Content-Disposition','attachment',filename=file.split("\\")[-1]) #定义附件显示的方式, 通过split方法把附件路径最后的文件名抓取出来
msg.attach(attachfile) #粘贴对象到邮件中
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = ",".join(msg_to)
smtp = smtplib.SMTP(host="smtp.office365.com")
try:
smtp.connect(host="smtp.office365.com",port=587) #邮件服务器及端口号
smtp.ehlo()
smtp.starttls()
smtp.login(msg_from, passwd) #登录SMTP服务器
smtp.sendmail(msg_from, msg_to, msg.as_string())#发邮件 as_string()把MIMEText对象变成str
print ("发送成功")
except Exception as e:
print ("发送失败,{0}".format(e))
finally:
smtp.quit()
if __name__ == "__main__":
read_content=mailcontent() #读取配置txt文件中的所有内容
receiver=read_content[0] #第一个元素为收件人列表
subject=read_content[1] #第二个元素为邮件标题
content=read_content[2] #第三个元素为邮件内容
content="\n".join(content)
att=CheckAtt() #读取附件文件列表清单
sendmail(receiver,subject, content, att)
网友评论