如何在Python中使用email.mime.text发送带有邮件抄送的中文邮件
发布时间:2024-01-11 10:35:47
在Python中使用email.mime.text模块发送带有邮件抄送的中文邮件可以通过以下步骤实现:
1. 导入所需的模块:smtplib, email.mime.multipart, email.mime.text。
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText
2. 创建邮件对象,并设置发件人、收件人、抄送人、主题等信息。
msg = MIMEMultipart() msg['From'] = 'sender@example.com' msg['To'] = 'receiver@example.com' msg['Cc'] = 'cc@example.com' msg['Subject'] = '中文邮件测试'
3. 创建邮件正文对象,并将中文内容以纯文本形式添加到邮件正文中。
body = '这是一封中文邮件的测试内容。' msg.attach(MIMEText(body, 'plain', 'utf-8'))
4. 创建SMTP服务器对象,并登录到发件人邮箱。
smtp_server = 'smtp.example.com' username = 'sender@example.com' password = 'password' server = smtplib.SMTP(smtp_server) server.login(username, password)
5. 发送邮件并退出SMTP服务器。
server.send_message(msg) server.quit()
以下是完整的示例代码:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText smtp_server = 'smtp.example.com' username = 'sender@example.com' password = 'password' msg = MIMEMultipart() msg['From'] = 'sender@example.com' msg['To'] = 'receiver@example.com' msg['Cc'] = 'cc@example.com' msg['Subject'] = '中文邮件测试' body = '这是一封中文邮件的测试内容。' msg.attach(MIMEText(body, 'plain', 'utf-8')) server = smtplib.SMTP(smtp_server) server.login(username, password) server.send_message(msg) server.quit()
注意事项:
- 请将smtp_server、username和password替换为实际的SMTP服务器地址、发件人邮箱地址和密码。
- 如果需要发送多个抄送人,可以使用逗号分隔多个邮箱地址。
- 中文邮件内容需要使用utf-8编码。
