python: smtplib使用实例
2020-11-12 本文已影响0人
luffynoonepiece
导入依赖
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
正文及寄送和接收者
msg = MIMEMultipart()
text = '正文'
sender = 'XXX@YY.com'
receivers = ['XXXX@YY.com']
content = MIMEText(text)
msg['From'] = Header(sender, 'utf-8')
msg['To'] = Header('XXXX', 'utf-8') # 这里是信件里收件者栏位的内容,并非显示真实的收件者
subject = '主题'
msg['Subject'] = Header(subject, 'utf-8')
# 下面是文字部分,也就是纯文本
puretext = MIMEText(text)
msg.attach(puretext)
# 添加Excel附件
xlsxpart = MIMEApplication(open(path, 'rb').read())
xlsxpart["Content-Type"] = 'application/octet-stream'
xlsxpart.add_header('Content-Disposition', 'attachment', filename=path)
msg.attach(xlsxpart)
寄送信件
try:
client = smtplib.SMTP()
client.connect('xxx@yy.com', 25) # 参数是SMTP 服务器主机以及默认端口25
# 注意:有些服务器需要login
client.sendmail(sender, receivers, msg.as_string())
client.quit()
print('带有各种附件的邮件发送成功。')
except smtplib.SMTPRecipientsRefused:
print('Recipient refused')
except smtplib.SMTPAuthenticationError:
print('Auth error')
except smtplib.SMTPSenderRefused:
print('Sender refused')
except smtplib.SMTPException as e:
print(e)
蟹蟹.jpg