python 发邮件 图片作附件
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage # 邮件发件人和收件人信息 sender_email = '你的Gmail地址' sender_password = '你的Gmail密码' recipient_email = '收件人邮箱地址' # 构造邮件内容 message = MIMEMultipart() message['From'] = sender_email message['To'] = recipient_email message['Subject'] = 'Python发送邮件测试' # 邮件正文 text = MIMEText('这是一封Python发送的邮件') message.attach(text) # 添加图片作为附件 with open('image.png', 'rb') as f: image_data = f.read() image = MIMEImage(image_data, name='image.png') message.attach(image) # 发送邮件 smtp_server = 'smtp.gmail.com' smtp_port = 587 smtp_connection = smtplib.SMTP(smtp_server, smtp_port) smtp_connection.starttls() smtp_connection.login(sender_email, sender_password) smtp_connection.sendmail(sender_email, recipient_email, message.as_string()) smtp_connection.quit()