python 读取文件内容向多人发邮件

# -*- coding: utf-8 -*-

import smtplib
import email.charset

chst = email.charset.Charset(input_charset = 'utf-8')

# header里分别定义发件人,收件人(收件人如果是多个,用list即可)以及邮件主题。
header=("From:%s\nTo:%s\nSubject:%s\n\n" % ("[email protected]", ["[email protected]","[email protected]"], chst.header_encode("Data Monitoring")))

# 打开绝对路径下的目标文档后读取并保存至msg这个多行str变量里。
f = open("/mnt/home/biwenchong/upload/upload.state",'r')
msg = ''' '''
while True:
    line = f.readline()
    msg += line.strip()+'\n'
    if not line:
        break
f.close()

# 对header和msg邮件正文进行utf-8编码,指定发信人的smtp服务器,并输入邮箱密码进行登录验证,最后发送邮件。

content = header.encode('utf-8') + msg.encode('utf-8')
smtp = smtplib.SMTP("smtp.163.com")
smtp.login("[email protected]","邮箱密码")
smtp.sendmail('[email protected]',['[email protected]','[email protected]'], content)
smtp.quit()

# 如果出现550 User has no permission的原因是由于163邮箱登录被拒绝了,解决的方法:登录163邮箱,在设置里把客户端授权码开启即可。

猜你喜欢

转载自blog.csdn.net/Gu_zhi/article/details/82693312