from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText
sender = 'sass1s@126.com'
receivers = ['2063198253@qq.com']
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']
必须是发件人的邮箱,如sass1s@126.com
message['To'] = Header('Erqing', 'utf-8')
message['To']
的值直接是字符串就行,可以是任意字符串。或者该行代码去掉也行。
修改后的代码如下:
from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText
sender = 'sass1s@126.com'
receivers = ['sass1s@126.com', '2063198253@qq.com']
message = MIMEText('示例代码.', 'plain', 'utf-8')
message['From'] = 'sass1s@126.com' # 不能用Header('sass1s@126.com', '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'] = 'sass1s@126.com'
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 = 'sass1s@126.com'
receivers = ['sass1s@126.com', '2063198253@qq.com']
smtper.login(sender, '替换为你的授权码')
smtper.sendmail(sender, receivers, message.as_string())
smtper.quit()
print('发送完成')
网友评论