1. 程式人生 > >python3使用smtplib發郵件被退回

python3使用smtplib發郵件被退回

背景:公司自己的郵件伺服器,不支援ssl

退回資訊:

This is the mail system at host mail.*****.net.cn.

I'm sorry to have to inform you that your message could not
be delivered to one or more recipients. It's attached below.

For further assistance, please send mail to postmaster.

If you do so, please include this problem report. You can
delete your own text from the attached returned message.

                  The mail system

<
[email protected]
*****.net.cn>: host 127.0.0.1[127.0.0.1] said: 554 5.6.0 Reject, id=19530-16 - BAD HEADER (in reply to end of DATA command) Reporting-MTA: dns; mail.*****.net.cn X-Postfix-Queue-ID: 899B32129B X-Postfix-Sender: rfc822; [email protected]*****.net.cn Arrival-Date: Thu, 12 Jul 2018 16:31:42 +0800 (CST) Final-Recipient: rfc822;
[email protected]
*****.net.cn Original-Recipient: rfc822;[email protected]*****.net.cn Action: failed Status: 5.6.0 Remote-MTA: dns; 127.0.0.1 Diagnostic-Code: smtp; 554 5.6.0 Reject, id=19530-16 - BAD HEADER 發件人: [email protected]*****.net.cn 主題: test 收件人: [email protected]*****.net.cn test

程式碼是百度找來的,也從沒配置過郵件伺服器,對郵件的運作流程完全不懂,關鍵的錯誤資訊就是'BAD HEADER',意為錯誤的報頭,試了幾天終於找到解決辦法,需要配置一個郵件的date,程式碼:

msg_from = '傳送人'
passwd = '密碼'
msg_to = '收件人'        
msg = MIMEText('內容')
msg['Subject'] = '標題'
msg['From'] = msg_from
msg['Date'] = Header('時間', 'utf-8')  # 時間可以這麼獲取:datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
msg['To'] = msg_to
s = smtplib.SMTP(self.mail_server, int(self.mail_port))
s.login(msg_from, passwd)
s.sendmail(msg_from, msg_to, msg.as_string())

不明白為什麼官方文件裡沒提msg['date']這個引數,真是踩了個深坑。