Python中如何创建和发送带附件的邮件
发布时间:2023-12-14 11:47:32
在Python中,可以使用smtplib和email模块来创建和发送带附件的邮件。下面是一个示例代码,说明了如何使用Python发送带附件的邮件。
首先,我们需要导入以下必要的模块:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication
创建邮件的函数如下所示:
def send_email(sender, receiver, subject, message, attachment):
# 创建MIMEMultipart对象,并设置邮件的主题、发件人和收件人
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
# 创建一个MIMEText对象,并设置邮件的正文内容
body = MIMEText(message)
msg.attach(body)
# 创建一个MIMEApplication对象,并读取附件文件的内容
with open(attachment, "rb") as f:
attach = MIMEApplication(f.read())
# 设置附件的文件名
attach.add_header('Content-Disposition', 'attachment', filename=attachment)
msg.attach(attach)
# 创建SMTP连接,并发送邮件
smtp_server = 'smtp.gmail.com'
smtp_port = 587
smtp_user = 'your_email@gmail.com'
smtp_password = 'your_password'
try:
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
smtp_obj.starttls()
smtp_obj.login(smtp_user, smtp_password)
smtp_obj.sendmail(sender, receiver, msg.as_string())
smtp_obj.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("邮件发送失败")
在上面的代码中,我们首先创建了一个MIMEMultipart对象,用于存储邮件的各个组成部分。然后,我们设置了邮件的主题、发件人和收件人,并附加了正文内容。接下来,我们创建了一个MIMEApplication对象,并读取附件文件的内容,然后将附件添加到邮件中。最后,我们使用smtplib.SMTP对象建立SMTP连接,并发送邮件。
要使用上述代码发送带附件的邮件,可以调用send_email函数,传递相应的参数。例如:
sender = 'your_email@gmail.com' receiver = 'recipient_email@example.com' subject = '测试邮件' message = '这是一封测试邮件,请查收。' attachment = 'path_to_attachment/file.zip' send_email(sender, receiver, subject, message, attachment)
在上面的示例代码中,我们指定了发件人、收件人、主题、正文内容和附件文件的路径。调用send_email函数后,会尝试建立SMTP连接,并发送邮件。如果邮件发送成功,会打印"邮件发送成功";如果邮件发送失败,会打印"邮件发送失败"。
需要注意的是,上述示例代码中使用的是Gmail的SMTP服务器和端口号,如果你使用的是其他邮箱提供商,需要更改SMTP服务器和端口号为相应的值,并使用正确的用户名和密码进行登录。
