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_with_attachment(sender_email, sender_password, receiver_email, subject, body, attachment_path):
# 创建邮件对象
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
# 添加正文
message.attach(MIMEText(body, "plain"))
# 添加附件
with open(attachment_path, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename= {attachment_path}")
message.attach(part)
# 发送邮件
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login(sender_email, sender_password)
server.send_message(message)
# 使用示例
sender_email = "your_email@example.com"
sender_password = "your_password"
receiver_email = "recipient@example.com"
subject = "邮件主题"
body = "邮件正文"
attachment_path = "path_to_attachment_file"
send_email_with_attachment(sender_email, sender_password, receiver_email, subject, body, attachment_path)
在上面的代码中,需要替换以下变量:
sender_email
:发件人邮箱地址sender_password
:发件人邮箱密码receiver_email
:收件人邮箱地址subject
:邮件主题body
:邮件正文attachment_path
:附件文件路径这段代码使用SMTP协议发送邮件,需要替换smtp.example.com
为你的邮件服务器的地址和端口号。请确保你的发件人邮箱开启了SMTP服务。
推荐的腾讯云相关产品是腾讯企业邮,它提供了稳定可靠的企业级邮件服务。你可以在腾讯云官网上找到更多关于腾讯企业邮的信息和产品介绍:腾讯企业邮
领取专属 10元无门槛券
手把手带您无忧上云