使用email.mime.imageMIMEImage()发送带有图片附件的邮件:Python实现
发布时间:2023-12-19 01:50:57
要发送带有图片附件的邮件,可以使用Python中的email和smtplib库。下面是一个使用email.mime.imageMIMEImage()发送带有图片附件的邮件的示例代码:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
# 邮件参数
sender_email = 'sender@example.com'
receiver_email = 'receiver@example.com'
subject = 'Email with Image Attachment'
smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'your_username'
password = 'your_password'
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 添加文本内容
text = "This email contains an image attachment"
msg.attach(MIMEText(text, 'plain'))
# 添加图片附件
with open('image.jpg', 'rb') as f:
img_data = f.read()
image = MIMEImage(img_data, name='image.jpg')
msg.attach(image)
# 发送邮件
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print("Email sent successfully")
except Exception as e:
print("Error sending email:", str(e))
finally:
server.quit()
请注意替换以下参数:
- sender_email和receiver_email:发件人和收件人的电子邮件地址。
- smtp_server和smtp_port:您的SMTP服务器和端口。
- username和password:您的SMTP服务器的用户名和密码。
- 'image.jpg':您要附加的图片的文件名。确保图像文件与脚本位于同一目录中。
在将上述代码复制到Python脚本中并运行之前,请确保已安装并导入了所需的库(email和smtplib)。
此示例代码创建一个MIMEMultipart邮件对象,并使用add_attach方法将图片附件添加到邮件中。然后,使用SMTP服务器发送邮件。
注意:您需要有一个可用的SMTP服务器来发送邮件,同时确保您具有正确的SMTP服务器参数和授权。
