欢迎访问宙启技术站
智能推送

Python发送带有自定义编码方式的MIMEText邮件

发布时间:2023-12-11 13:51:30

使用Python发送带有自定义编码方式的MIMEText邮件需要以下几个步骤:

1. 导入相应的模块:

import smtplib
from email.mime.text import MIMEText
from email.header import Header

2. 设置邮件发送和接收的相关信息:

sender = "from_address@example.com"
receiver = "to_address@example.com"
subject = "邮件主题"
smtp_server = "smtp.example.com"
smtp_port = 587
username = "username"
password = "password"

3. 创建邮件正文内容:

message = "邮件内容"
charset = "utf-8"
msg = MIMEText(message, "plain", charset)

4. 设置自定义编码方式:

msg["Content-Type"] = "text/plain; charset=my_custom_encoding"
msg["Content-Transfer-Encoding"] = "quoted-printable"

在这里,my_custom_encoding可以替换为你要使用的自定义编码方式,例如UTF-8,GBK等。quoted-printable是一种常见的编码方式,可以处理多语言字符。

5. 设置邮件头部信息:

msg["From"] = Header("发件人名称", charset)
msg["To"] = Header("收件人名称", charset)
msg["Subject"] = Header(subject, charset)

6. 发送邮件:

try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.ehlo()
    server.starttls()
    server.login(username, password)
    server.sendmail(sender, receiver, msg.as_string())
    server.quit()
    print("邮件发送成功")
except Exception as e:
    print("邮件发送失败:", str(e))

以上代码示例了如何使用自定义编码方式发送一个简单的纯文本邮件。你可以根据自己的需求进行修改和扩展,例如添加附件、HTML格式的邮件内容等。

注意:在使用SMTP发送邮件之前,你需要确保已经在邮件服务器上设置了相应的配置,并且SMTP服务可用。

希望这个例子对你有所帮助!