Python傳送網易郵件554錯誤解決
阿新 • • 發佈:2019-01-03
python傳送網易郵件出現554錯誤原因很多,記錄本次遇到的問題
貼上程式碼
在msgRoot中之前沒有加入From和To地址,傳送郵件就返回554,後面加上並與smtp.sendmail中保持一致後傳送成功#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()