使用Python将文件附加到电子邮件中,可以使用Python的内置库smtplib和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
def send_email(sender_email, sender_password, receiver_email, subject, message, file_path):
# 创建一个多部分(multipart)的邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(message, 'plain'))
# 添加附件
attachment = open(file_path, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % file_path)
msg.attach(part)
# 发送邮件
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
server.send_message(msg)
server.quit()
# 示例用法
sender_email = "your_email@gmail.com"
sender_password = "your_password"
receiver_email = "recipient_email@gmail.com"
subject = "附件测试"
message = "这是一封带附件的测试邮件"
file_path = "path_to_your_file"
send_email(sender_email, sender_password, receiver_email, subject, message, file_path)
上述代码中,需要替换以下变量的值:
sender_email
:发送者的邮箱地址sender_password
:发送者邮箱的密码receiver_email
:接收者的邮箱地址subject
:邮件主题message
:邮件正文内容file_path
:要附加的文件路径这段代码使用Gmail的SMTP服务器发送邮件,如果你使用其他邮箱,需要修改SMTP服务器的地址和端口号。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)
领取专属 10元无门槛券
手把手带您无忧上云