使用Python的MIMEApplication()在邮件中添加Excel文件附件
发布时间:2023-12-24 23:40:39
在Python中,我们可以使用MIMEApplication模块来添加Excel文件作为邮件附件。下面是一个使用示例:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 设置SMTP服务器信息
smtp_server = "smtp.example.com"
smtp_port = 587
smtp_username = "your_username"
smtp_password = "your_password"
# 发送邮件函数
def send_email(sender, receiver, subject, message, attachment_path):
# 创建邮件
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
# 添加文本内容
msg.attach(MIMEText(message, 'plain'))
# 添加附件
with open(attachment_path, "rb") as attachment:
part = MIMEApplication(
attachment.read(),
Name="attachment.xlsx"
)
part['Content-Disposition'] = f'attachment; filename="{part["Name"]}"'
msg.attach(part)
# 发送邮件
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
server.send_message(msg, sender, receiver)
server.quit()
print("邮件发送成功")
except Exception as e:
print(f"邮件发送失败: {e}")
# 调用函数发送邮件
sender_email = "sender@example.com"
receiver_email = "receiver@example.com"
email_subject = "测试邮件"
email_message = "这是一封测试邮件,请查收。"
attachment_path = "path/to/attachment.xlsx"
send_email(sender_email, receiver_email, email_subject, email_message, attachment_path)
在上面的例子中,我们首先导入了需要使用的模块,包括smtplib用于发送邮件,MIMEText用于添加文本内容,MIMEMultipart用于创建多部分消息,以及MIMEApplication用于添加附件。
然后,我们定义了一个名为send_email的函数,该函数接受发件人、收件人、主题、消息内容和附件路径作为参数。在函数内部,我们首先创建了一个MIMEMultipart对象,并设置了发件人、收件人和主题字段。
接下来,我们使用MIMEText将消息内容添加到邮件中。然后,我们使用open函数打开附件文件,并使用MIMEApplication将其添加到邮件中。要设置附件的文件名,我们可以使用Name属性。最后,我们使用Content-Disposition设置附件的显示方式。
最后,我们通过SMTP服务器发送邮件。首先,我们创建一个SMTP对象,然后使用starttls启用TLS加密。接下来,我们使用login方法登录到SMTP服务器,并使用send_message将邮件发送给收件人。最后,我们使用quit方法关闭SMTP连接。
要发送邮件,我们只需调用send_email函数,并提供发件人邮箱、收件人邮箱、主题、消息内容和附件路径作为参数。在本例中,我们使用的SMTP服务器是smtp.example.com,端口是587。你需要替换成你自己的SMTP服务器信息。
希望以上示例对你有帮助!如果你有任何问题,请随时提问。
