使用MIMEMultipart()在Python中发送带有文本文件附件的邮件
发布时间:2023-12-25 18:32:22
在Python中使用MIMEMultipart()发送带有文本文件附件的邮件可以按照以下步骤进行:
1. 首先,导入必要的库:smtplib用于发送邮件、email.mime.multipart和email.mime.text用于构建邮件内容。
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText
2. 创建一个MIMEMultipart对象,它将作为我们要发送的邮件的容器。
msg = MIMEMultipart()
3. 设置邮件的主题、发件人、收件人和正文。
msg['Subject'] = 'Email with Text File Attachment' msg['From'] = 'sender@example.com' msg['To'] = 'recipient@example.com' body = 'Please find the attached text file.' msg.attach(MIMEText(body, 'plain'))
4. 读取并附加要发送的文本文件。
filename = 'text_file.txt'
attachment = open(filename, 'rb')
part = MIMEText(attachment.read(), 'plain')
part.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(part)
attachment.close()
5. 设置邮件服务器的信息,并使用SMTP协议发送邮件。
smtp_server = 'smtp.example.com' username = 'sender@example.com' password = 'password' server = smtplib.SMTP(smtp_server, port=587) server.starttls() server.login(username, password) server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit()
完整的代码示例如下:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['Subject'] = 'Email with Text File Attachment'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
body = 'Please find the attached text file.'
msg.attach(MIMEText(body, 'plain'))
filename = 'text_file.txt'
attachment = open(filename, 'rb')
part = MIMEText(attachment.read(), 'plain')
part.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(part)
attachment.close()
smtp_server = 'smtp.example.com'
username = 'sender@example.com'
password = 'password'
server = smtplib.SMTP(smtp_server, port=587)
server.starttls()
server.login(username, password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
请确保替换示例中的实际邮箱地址、SMTP服务器和认证信息,以适应您的具体需求。
