在使用Python进行邮件发送时,可以使用email库中的MIMEBase和MIMEApplication类来实现将文件作为附件保存到邮件中。以下是一个示例代码,展示了如何使用这些类来实现忽略“保存前”和“保存后”。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email import encoders
# 附件文件路径
file_path = "path/to/attachment.pdf"
# 创建邮件对象
msg = MIMEMultipart()
# 添加附件
with open(file_path, 'rb') as file:
part = MIMEApplication(file.read(), Name=file_path)
part['Content-Disposition'] = 'attachment; filename="attachment.pdf"'
msg.attach(part)
# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_username'
smtp_password = 'your_password'
sender_email = 'sender@example.com'
receiver_email = 'receiver@example.com'
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.ehlo()
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
在上述代码中,我们使用MIMEApplication类来读取附件文件内容,并将其添加到邮件对象中作为附件。同时,我们还设置了附件的文件名以及Content-Disposition头部字段,以确保附件在邮件中正确显示。最后,我们使用smtplib库来连接SMTP服务器并发送邮件。
这样做的好处是,我们直接读取附件文件内容,并将其作为二进制数据保存到邮件中,而不需要“保存前”和“保存后”的过程。
上一篇:保存为EPS格式时回归线非透明。
下一篇:保存未格式化的XML文件