要使用Python发送带有附件的电子邮件,您需要
除了smtplib之外,还可以使用电子邮件模块。
这个
smtplib.sendmail()方法
不直接处理附件,因此您需要构建包含附件的电子邮件。
我为您提供了下面的完整代码供您参考,您可以根据自己的意愿进行编辑:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
# Email configuration
filename = 'image.png'
my_user = '[email protected]'
my_pass = 'my app code'
sent_to = '[email protected]' # Use your actual recipient email
# Creating email message
msg = MIMEMultipart()
msg['From'] = my_user
msg['To'] = sent_to
msg['Subject'] = 'Subject: Test Email with Attachment'
# Email body text
body = 'This is a test email with an attachment.'
msg.attach(MIMEText(body, 'plain'))
# Attach the file
attachment = open(filename, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename= {filename}')
msg.attach(part)
# Send the email
try:
smtpserver = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtpserver.login(my_user, my_pass)
smtpserver.send_message(msg)
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {e}")
finally:
smtpserver.quit()
attachment.close()
如果这段代码解决了你的问题,那么请为我的答案投上赞成票(点击顶部和旁边的上箭头)。