使用email.mime.text发送带附件的中文邮件
发布时间:2024-01-11 10:32:18
以下是使用email.mime.text发送带附件的中文邮件的使用例子:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# 配置发件人、收件人和SMTP服务器
from_addr = 'sender@example.com'
to_addr = 'recipient@example.com'
smtp_server = 'smtp.example.com'
# 创建邮件对象
msg = MIMEMultipart()
# 设置邮件主题
subject = '测试邮件'
msg['Subject'] = subject
# 设置发件人和收件人
msg['From'] = from_addr
msg['To'] = to_addr
# 创建邮件正文
text = """
这是一封测试邮件,带有附件。
附件是一张图片。
"""
body = MIMEText(text, 'plain', 'utf-8')
msg.attach(body)
# 创建并添加附件
file_path = 'path/to/image.jpg'
attachment = MIMEApplication(open(file_path, 'rb').read())
attachment.add_header('Content-Disposition', 'attachment', filename='中文图片.jpg')
msg.attach(attachment)
# 发送邮件
try:
server = smtplib.SMTP(smtp_server)
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
print('邮件发送成功')
except smtplib.SMTPException:
print('邮件发送失败')
注意,你需要替换以下参数:
- from_addr:发件人的Email地址
- to_addr:收件人的Email地址
- smtp_server:SMTP服务器的地址
- file_path:附件文件的路径
此代码示例通过创建一个MIMEMultipart对象来实现带附件的邮件。在创建邮件正文和附件时,使用MIMEText和MIMEApplication来指定各自的类型,并使用msg.attach()方法将它们附加到邮件对象上。最后,使用server.sendmail()发送邮件。
如果发送成功,将打印出"邮件发送成功",否则将打印出"邮件发送失败"。
