如何在Python中使用email.mime.text发送中文邮件的附件
发布时间:2024-01-11 10:39:59
在Python中使用email.mime.text模块发送带有中文附件的邮件可以通过以下步骤完成:
1. 导入所需的模块:
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header
2. 设置发件人、收件人和邮件主题:
sender = 'sender@example.com' receiver = 'receiver@example.com' subject = '中文邮件附件示例'
3. 创建一个MIMEMultipart对象来包含邮件内容和附件:
message = MIMEMultipart()
message['From'] = Header('发件人姓名', 'utf-8')
message['To'] = Header('收件人姓名', 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
4. 添加邮件正文:
message.attach(MIMEText('这是一封带有中文附件的邮件示例', 'plain', 'utf-8'))
5. 添加附件到邮件:
attachment = MIMEText(open('附件文件.txt', 'rb').read(), 'base64', 'utf-8')
attachment["Content-Type"] = 'application/octet-stream'
attachment["Content-Disposition"] = 'attachment; filename="中文附件.txt"'
message.attach(attachment)
6. 发送邮件:
try:
smtpObj = smtplib.SMTP()
smtpObj.connect('smtp.example.com', 25)
smtpObj.login('username', 'password')
smtpObj.sendmail(sender, receiver, message.as_string())
smtpObj.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("Error:无法发送邮件")
完整的使用例子如下:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
sender = 'sender@example.com'
receiver = 'receiver@example.com'
subject = '中文邮件附件示例'
message = MIMEMultipart()
message['From'] = Header('发件人姓名', 'utf-8')
message['To'] = Header('收件人姓名', 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
message.attach(MIMEText('这是一封带有中文附件的邮件示例', 'plain', 'utf-8'))
attachment = MIMEText(open('附件文件.txt', 'rb').read(), 'base64', 'utf-8')
attachment["Content-Type"] = 'application/octet-stream'
attachment["Content-Disposition"] = 'attachment; filename="中文附件.txt"'
message.attach(attachment)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect('smtp.example.com', 25)
smtpObj.login('username', 'password')
smtpObj.sendmail(sender, receiver, message.as_string())
smtpObj.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("Error:无法发送邮件")
确保将示例中的发件人、收件人、附件文件、SMTP服务器和登录凭据替换为实际的值。
