import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication

邮件发送者

sender = 'example@example.com'

邮件接收者

receiver = 'example2@example.com'

邮件主题

subject = '测试邮件'

邮件正文

content = '这是一封测试邮件。'

创建一个带附件的实例

message = MIMEMultipart() message['From'] = sender message['To'] = receiver message['Subject'] = subject

添加正文

text = MIMEText(content) message.attach(text)

添加附件

filename = 'test.txt' attachment = MIMEApplication(open(filename, 'rb').read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(attachment)

发送邮件

try: smtpObj = smtplib.SMTP('smtp.example.com') smtpObj.login('example', 'password') smtpObj.sendmail(sender, receiver, message.as_string()) print('邮件发送成功') except smtplib.SMTPException as e: print('邮件发送失败,错误信息:', e)

Python发送邮件代码示例:带附件

原文地址: https://www.cveoy.top/t/topic/lxar 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录