如何在Python中使用MIMEText()发送中文邮件
发布时间:2024-01-18 10:37:49
在Python中使用MIMEText()发送中文邮件需要先设置邮件的内容类型为"text/plain"或"text/html",并设置字符编码为"utf-8"。然后通过SMTP服务器发送邮件。
以下是一个具体的使用例子:
import smtplib from email.mime.text import MIMEText # 步:设置邮件内容及编码 mail_content = "这是一封中文邮件" text_subtype = 'plain' # 邮件内容的类型:纯文本或HTML charset = 'utf-8' # 邮件的编码 msg = MIMEText(mail_content, text_subtype, charset) msg['Subject'] = '中文邮件的主题' msg['From'] = 'sender@example.com' msg['To'] = 'recipient@example.com' # 第二步:连接SMTP服务器,登录邮箱 smtp_server = 'smtp.example.com' username = 'your_username' password = 'your_password' smtp_conn = smtplib.SMTP(smtp_server) smtp_conn.login(username, password) # 第三步:发送邮件 smtp_conn.sendmail(msg['From'], msg['To'], msg.as_string()) smtp_conn.quit()
在代码中,我们首先导入了smtplib和MIMEText模块。然后,设置邮件内容为中文,并指定邮件内容类型为纯文本,编码为utf-8,创建MIMEText对象。
接下来,设置邮件的主题、发件人和收件人等信息。
然后,我们连接SMTP服务器,并通过登录邮箱的用户名和密码进行登录。
最后,调用sendmail方法发送邮件,指定发件人、收件人和邮件内容。
请注意,实际使用中需要将smtp.example.com、your_username和your_password替换为实际的SMTP服务器地址、用户名和密码。
以上是一个简单的使用MIMEText()发送中文邮件的例子,希望能对您有所帮助。
