SMTP报错 smtplib.SMTPDataError: 554, smtplib.SMTPAuthenticationError: 535 廖雪峰案例BUG

# -*- coding: utf-8 -*-
"""
Created on Thu Apr 26 19:57:32 2018


@author: yyhhlancelot
"""
import smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart 
from email.mime.base import MIMEBase




# 输入Email地址和口令:
#from_addr = input('From: ')
sender = '[email protected]'
password = input('Password: ')
# 输入收件人地址:
#to_addr = input('To: ')
receiver = '[email protected]'
# 输入SMTP服务器地址:
#smtp_server = input('SMTP server: ')
subject = 'test6'
smtp_server = 'smtp.163.com'
#邮件对象
msg = MIMEMultipart()
msg.attach(MIMEText('<html><body><h1>Hello</h1>' +
    '<p>send by <a href="http://www.python.org">Python</a>...</p>' +
    '</body></html>', 'html', 'utf-8'))
msg['Subject'] = Header(subject, 'utf-8')  
msg['From'] = '[email protected] <[email protected]>'  
msg['To'] = 'yyhhlancelot <[email protected]>' 
#msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
# 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open('C:/Users/yyhhlancelot/Desktop/1.jpg', 'rb') as f:
    # 设置附件的MIME和文件名,这里是png类型:
    mime = MIMEBase('image', 'jpeg', filename='1.jpg')
    # 加上必要的头信息:
    mime.add_header('Content-Disposition', 'attachment', filename='1.jpg')
    mime.add_header('Content-ID', '<0>')
    mime.add_header('X-Attachment-Id', '0')
    # 把附件的内容读进来:
    mime.set_payload(f.read())
    # 用Base64编码:
    encoders.encode_base64(mime)
    # 添加到MIMEMultipart:
    msg.attach(mime)






server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
server.set_debuglevel(1)
server.login(sender, password)
server.sendmail(sender, [receiver], msg.as_string())
server.quit()

上述代码是通过163邮箱发送到qq邮箱。服务器为163服务器。

注意事项:

1.报错535:

是因为未将POP3/SMTP服务开启。此项通过在163邮箱内 设置 获取授权码  打开,通过授权码可以进行第三方登录。此处的Password填写授权码。

2.报错554:

第一种情况:缺失发件人和主题,将msg['Subject']   msg['From']  msg['To'] 几行添加。

第二种情况:网络的问题。当家里的网络出现问题时,切换成手机热点试试;当手机热点出现问题时,切换成家里的网络试试。这个问题真的把我弄得吐血。

猜你喜欢

转载自blog.csdn.net/yyhhlancelot/article/details/80100398