python实现读取本地多个TXT文件内容并发送邮件

代码分析:
	1、主要是使用python中内stmplib模块,通过该模块可以实现邮件的发送
	2、在发送之前需要进个人邮箱中进行设置,检查POP3/SMTP/IMAP是否是打开状态	
	3、若未开启,则需要通过手机验证,然后重新设置客户端授权密码。
 
  
 
  
 
  
#!/usr/bin/python
# -*- coding:utf-8 -*-

import os
import fnmatch
import smtplib
from email.mime.text import MIMEText
from email.header import Header

mail_host = "smtp.163.com"
user = "[email protected]"
passwd = "****"

send = '[email protected]'
rec = ['[email protected]']
subject = 'python email test'

# 将读取的到不同文件的内容输出到datadata = ''

path = "f:/nginx-out"
for _, _, filenames in os.walk(path):
    for filename in fnmatch.filter(filenames, "part-*"):
        with open(os.path.join(path, filename)) as src:
            data = data + ''.join(src.readlines())
src.close()

# print data

msg = MIMEText(data, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
# 此处需要按照个人邮件地址填写,否则会出现在垃圾箱里
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
try:
    smtp = smtplib.SMTP()
    smtp.connect(mail_host, 25)
    smtp.login(user, passwd)
    smtp.sendmail(send, rec, msg.as_string())
    print("发送邮件成功")
    smtp.quit()
except smtplib.SMTPException:
    print("Error: 无法发送邮件")

你可能感兴趣的:(python)