在Python中使用MIMEBase()发送带字体文件附件的邮件
发布时间:2024-01-17 01:33:08
在Python中使用MIMEBase()发送带字体文件附件的邮件,需要使用email和smtplib模块。下面是一个示例代码:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
# 发件人和收件人的邮箱地址
sender_email = "sender@example.com"
receiver_email = "receiver@example.com"
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = "带字体文件附件的邮件"
# 添加正文
body = "这是一封带字体文件附件的邮件"
msg.attach(MIMEText(body, 'plain'))
# 打开字体文件
font_filepath = "path_to_font_file.ttf"
with open(font_filepath, "rb") as font_file:
# 创建MIMEBase对象,并设置类型为application/octet-stream
attachment = MIMEBase("application", "octet-stream")
# 将字体文件内容作为附件添加到MIMEBase对象
attachment.set_payload(font_file.read())
# 添加Content-Disposition头部,指定文件名
attachment.add_header("Content-Disposition", "attachment", filename="font_file.ttf")
# 对附件进行编码
encoders.encode_base64(attachment)
# 添加附件到邮件对象
msg.attach(attachment)
# 发送邮件
smtp_server = "smtp.example.com"
smtp_port = 587
smtp_username = "your_username"
smtp_password = "your_password"
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print("邮件发送成功!")
请注意,该示例代码中的smtp_server,smtp_port,smtp_username和smtp_password需要根据你的实际情况进行替换。此外,path_to_font_file.ttf也需要替换为字体文件的实际路径。
这样就可以使用MIMEBase()发送带字体文件附件的邮件了。
