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(''):]
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', '')
msgRoot.attach(msgImage1)
img2_path = 'xxxxx'
msgImage2 = send_email.read_img(img2_path)
msgImage2.add_header('Content-ID', '')
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中保持一致后发送成功