使用Python生成带有自定义内容类型的MIMEText邮件
发布时间:2023-12-11 13:51:49
在Python中,我们可以使用email模块来生成带有自定义内容类型的MIMEText邮件。下面是一个使用例子:
首先,我们需要导入必要的模块:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText
然后,我们可以创建一个MIMEMultipart对象作为邮件的容器,并设置邮件的发送者、接收者、主题等信息:
msg = MIMEMultipart() msg['From'] = 'sender@example.com' msg['To'] = 'recipient@example.com' msg['Subject'] = 'Testing email with custom content type'
接下来,我们可以创建一个MIMEText对象,并将自定义的内容类型和内容添加到该对象中:
custom_content_type = 'application/custom-content-type'
custom_content = 'This is a custom content type email.'
email_content = MIMEText(custom_content, _subtype='plain', _charset='utf-8')
email_content.add_header('Content-Type', custom_content_type)
最后,我们将MIMEText对象添加到邮件容器中,并使用smtplib模块发送该邮件:
msg.attach(email_content)
smtp_server = smtplib.SMTP('smtp.example.com')
smtp_server.login('username', 'password')
smtp_server.send_message(msg)
smtp_server.quit()
完整的代码如下:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'Testing email with custom content type'
custom_content_type = 'application/custom-content-type'
custom_content = 'This is a custom content type email.'
email_content = MIMEText(custom_content, _subtype='plain', _charset='utf-8')
email_content.add_header('Content-Type', custom_content_type)
msg.attach(email_content)
smtp_server = smtplib.SMTP('smtp.example.com')
smtp_server.login('username', 'password')
smtp_server.send_message(msg)
smtp_server.quit()
以上代码将生成一个带有自定义内容类型的邮件,并将其发送给指定的接收者。请注意,你需要将代码中的'sender@example.com'、'recipient@example.com'、'smtp.example.com'、'username'和'password'替换为实际的信息。
希望这个例子能帮助你生成带有自定义内容类型的MIMEText邮件。
