email用法

发布时间 2023-04-22 14:40:29作者: linux星

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

# 设置发件人和收件人
sender = 'example@gmail.com'
password = 'password'
receiver = 'example2@gmail.com'
# 设置邮件主题和正文
subject = 'Test Email'
text = 'This is a test email sent from Python.'

msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject

body = MIMEText(text)
msg.attach(body)

with open('image.jpg', 'rb') as f:
    img_data = f.read()
img = MIMEImage(img_data, name='image.jpg')
msg.attach(img)

try:
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(sender, password)
    server.sendmail(sender, receiver, msg.as_string())
    print('Email sent successfully.')
except Exception as e:
    print(e)
finally:
    server.quit()