附件其实就是另一种格式的MIME,所以在构造邮件消息体的时候需要使用MIMEMultipart来构造复合类型的消息体,然后把文本和附件一个一个地加进去

举个例子吧。嗯那个超链接的问题还是老样子,没解决

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

sender = 'xxxx@xx.xx'
password = 'xxxxx'
receiver = ['xxx@xx.xx', ]
message = MIMEMultipart()
message['From'] = Header(sender, 'utf-8')
message['To'] = Header('邮件', 'utf-8')
message['Subject'] = 'Python SMTP 发送带附件的邮件'
mail_msg = '''
<p>使用python发送邮件</p>
<br>
<p><a href="http://www.baidu.com">这是一个超链接</p>
'''
message.attach(MIMEText(mail_msg, 'html', 'utf-8'))
attached_file = MIMEText(open(__file__, encoding='utf-8').read(), 'base64', 'utf-8')
attached_file['Content-Disposition'] = 'attachment;filename="mail.py"'
message.attach(attached_file)
try:
    smtp = smtplib.SMTP_SSL('smtp.qiye.aliyun.com', 465)
    smtp.login(sender, password)
    smtp.sendmail(sender, receiver, message.as_string())
    print('邮件已发送!')

except smtplib.SMTPException as e:
    print('出现错误!', e.args[1].decode('gbk'))

于是乎,邮箱就收到邮件了

你也可能喜欢

发表评论