Python发送网易邮件554错误解决

python发送网易邮件出现554错误原因很多,记录本次遇到的问题

贴上代码

#coding: utf-8
import smtplib,sys,re
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

class send_email(object):
    def except_msg(self):
        s = sys.exc_info()
        errInfo = "Error %s happened in line %d at safe_scan_ci" % (s[1], s[2].tb_lineno)
        print errInfo

    def read_img(self, img_path):
        msgImage = ''
        try:
            fp = open(img_path, 'rb')
            msgImage = MIMEImage(fp.read())
            fp.close()
        except:
            self.except_msg()
        return msgImage

if __name__ == '__main__':
    send_email = send_email()
    sender = 'xxxxxx'
    receiver = 'xxxxxx'
    subject = 'python email'
    smtpserver = 'smtp.163.com'
    username = 'xxxxxx'
    password = 'xxxxxx'

    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = sender  #之前没有写From和To,发送邮件出现554错误
    msgRoot['To'] = receiver

    htmlStr = ''
    with open('xxxxx','r') as html_file:
        htmlTextList = html_file.readlines()
    for htmlText in htmlTextList:
        htmlText = re.sub('<img .*?src="collapse.png"','<img src="cid:image1"',htmlText)
        htmlText = re.sub('<img .*?src="expand.png"','<img src="cid:image2"', htmlText)
        htmlStr = htmlStr + htmlText
    section1 = htmlStr[:htmlStr.index('.page_details')]
    section2 = htmlStr[htmlStr.index('</style>'):]
    htmlStr = section1 + section2
    msgText = MIMEText(htmlStr, 'html', 'utf-8')
    # msgText = MIMEText("hello email", 'text', 'utf-8')

    msgRoot.attach(msgText)

    img1_path = 'xxxxx'
    msgImage1 = send_email.read_img(img1_path)
    msgImage1.add_header('Content-ID', '<image1>')
    msgRoot.attach(msgImage1)

    img2_path = 'xxxxx'
    msgImage2 = send_email.read_img(img2_path)
    msgImage2.add_header('Content-ID', '<image2>')
    msgRoot.attach(msgImage2)

    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msgRoot.as_string())
    smtp.quit()
在msgRoot中之前没有加入From和To地址,发送邮件就返回554,后面加上并与smtp.sendmail中保持一致后发送成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大杀风景

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值