使用Python的email.MIMEBase模块发送带有附件的邮件
发布时间:2023-12-14 03:35:44
发送带有附件的邮件使用Python的email模块是非常简单的。首先,我们需要导入需要的模块:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders
接下来,我们需要设置一些基本的参数,如发送者、收件人、主题和身份验证信息:
fromaddr = "sender@gmail.com" toaddr = "receiver@gmail.com" subject = "Testing Email with Attachment" username = "your_username" password = "your_password"
然后,我们可以创建一个MIMEMultipart对象来表示整个邮件,并设置一些基本的信息:
msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = subject
接下来,我们可以添加正文内容到邮件中:
body = "This is the body of the email" msg.attach(MIMEText(body, 'plain'))
然后,我们可以打开要添加为附件的文件,并将其添加到邮件中:
attachment = open("path_to_attachment_file", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
最后,我们可以使用smtplib模块来发送邮件:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(username, password)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
下面是一个完整的例子,演示如何使用email模块发送带有附件的邮件:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "sender@gmail.com"
toaddr = "receiver@gmail.com"
subject = "Testing Email with Attachment"
username = "your_username"
password = "your_password"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = subject
body = "This is the body of the email"
msg.attach(MIMEText(body, 'plain'))
filename = "attachment.pdf"
attachment = open("path_to_attachment_file", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(username, password)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
请确保将sender@gmail.com和receiver@gmail.com替换为实际的发送者和接收者的电子邮件地址。同时,也要将your_username和your_password替换为您的SMTP服务器的用户名和密码。
以上就是使用Python的email.MIMEBase模块发送带有附件的邮件的例子。您可以根据自己的需求进行修改和扩展。
