使用smtp发送邮件

参考https://github.com/jackfrued/Python-100-Days/blob/master/Day01-15/14.%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%E5%85%A5%E9%97%A8%E5%92%8C%E7%BD%91%E7%BB%9C%E5%BA%94%E7%94%A8%E5%BC%80%E5%8F%91.md的代码,写出如下发送邮件代码:

from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText

sender = '[email protected]'
receivers = ['[email protected]']

message = MIMEText('用Python发送邮件的示例代码.', 'plain', 'utf-8')
message['From'] = Header('Daqing', 'utf-8')  
message['To'] = Header('Erqing', 'utf-8')
message['Subject'] = Header('示例代码实验邮件', 'utf-8')
smtper = SMTP('smtp.126.com')
# smtper.connect('smtp.126.com')

smtper.login(sender, '替换为你的126邮箱的授权码')
smtper.sendmail(sender, receivers, message.as_string())
print('邮件发送完成!')

上述代码有两个地方错误:

message['From'] = Header('Daqing', 'utf-8')

message['From']必须保留,但是不能放在Header中,直接使用字符串就行。并且message['From']必须是发件人的邮箱,如[email protected]

message['To'] = Header('Erqing', 'utf-8')

message['To']的值直接是字符串就行,可以是任意字符串。或者该行代码去掉也行。
修改后的代码如下:

from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText

sender = '[email protected]'
receivers = ['[email protected]', '[email protected]']

message = MIMEText('示例代码.', 'plain', 'utf-8')
message['From'] = '[email protected]'  # 不能用Header('[email protected]', 'utf-8'), 否者报错554 SPM
# message['To'] = 'Erqing'
message['Subject'] = Header('示例代码实验邮件', 'utf-8')
smtper = SMTP('smtp.126.com')

smtper.login(sender, '替换为你的126邮箱授权码')
smtper.sendmail(sender, receivers, message.as_string())
print('邮件发送完成!')

运行后即可成功发送邮件。

发送带附件的邮件

以下代码可以实现带附件的邮件发送

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

message = MIMEMultipart()
text_content = MIMEText('附件中有本月数据,请查收', 'plain', 'utf-8')
message['Subject'] = Header('本月数据', 'utf-8')
message['From'] = '[email protected]'
message.attach(text_content)

with open('hello.txt', 'rb') as f:
    txt = MIMEText(f.read(), 'base64', 'utf-8')
    txt['Content-Type'] = 'text/plain'
    txt['Content-Disposition'] = 'attachment; filename=hello.txt'
    message.attach(txt)

with open('汇总数据.xlsx', 'rb') as f:
    xls = MIMEText(f.read(), 'base64', 'utf-8')
    xls['Content-Type'] = 'application/vnd.ms-excel'
    xls['Content-Disposition'] = 'attachment; filename=month-data.xlsx'
    message.attach(xls)


smtper = SMTP('smtp.126.com')
sender = '[email protected]'
receivers = ['[email protected]', '[email protected]']
smtper.login(sender, '替换为你的授权码')
smtper.sendmail(sender, receivers, message.as_string())
smtper.quit()
print('发送完成')

你可能感兴趣的:(使用smtp发送邮件)