使用Python 3.6发送电子邮件附件可以通过使用内置的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, message, attachment_path):
# 创建一个带附件的邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(message, 'plain'))
# 添加附件
attachment = open(attachment_path, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {attachment_path}")
msg.attach(part)
# 发送邮件
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(sender_email, sender_password)
server.send_message(msg)
# 使用示例
sender_email = "your_email@gmail.com"
sender_password = "your_password"
receiver_email = "recipient_email@example.com"
subject = "Sample Email with Attachment"
message = "This is a sample email with attachment."
attachment_path = "path_to_attachment_file"
send_email_with_attachment(sender_email, sender_password, receiver_email, subject, message, attachment_path)
上述代码中,需要替换以下变量的值:
sender_email
: 发件人的邮箱地址sender_password
: 发件人的邮箱密码receiver_email
: 收件人的邮箱地址subject
: 邮件主题message
: 邮件正文内容attachment_path
: 附件文件的路径这段代码使用Gmail的SMTP服务器发送邮件,如果你使用其他邮箱提供商,请相应地更改SMTP服务器的地址和端口号。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/etp)
领取专属 10元无门槛券
手把手带您无忧上云