Python发送多个附件和支持HTML及纯文本内容的 Email 实现

由于工作中经常需要收发电子邮件,例如每日(周)的工作报告,测试报告,监控告警,定时提醒等等,大都已电子邮件的形式发送。本文将实现一个 Python 的电子邮件发送类,支持发送多个附件(目录),HTML或纯文本内容,抄送收件人,多个接收者等功能。


代码实现

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C)  2015 By Thomas Hu.  All rights reserved.
@author : Thomas Hu
@version: 1.0
@created: 2015-05-17
'''
import base64
import httplib
import re
import os
import smtplib
from xml.etree import ElementTree
from email.utils import formatdate
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email import Encoders

class EmailSender(object):
    def __init__(self, smtp_server, smtp_port=0, verbose=False, debug_level=1, encoding="utf-8"):
        ''' Initiate the EmailSender.
        @param smtp_server: the Email SMTP server.
        @param smtp_port:   the Email SMTP server port, if use the default port(25), you can set it to 0 or 25.
        @param verbose:     show the processing information if set to 'True', default is 'False'.
        @param debug_level: set the smtplib debug level, if it's '0', will enable debug information.
        @param encoding:    the encoding or charset for email body text or attachment file name, default is "utf-8".
        '''
        self.server = smtp_server
        self.port = int(smtp_port)
        self.verbose = verbose
        self.debug_level = int(debug_level)
        self.encoding = encoding
        self.attachments = []

        #Create smtp instance
        self.smtp = smtplib.SMTP(self.server, self.port)
        self.smtp.set_debuglevel(self.debug_level)
        self.pr
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个任务需要多个步骤,以下是实现的一个简单示例: ```python import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # 定义发件人、收件人、主题、正文附件信息 sender = "your_email@your_domain.com" receiver = "recipient_email@recipient_domain.com" subject = "Test email" text = "Hello World!" attachment_path = "/path/to/attachment.txt" # 创建邮件对象并添加信息 message = MIMEMultipart() message["From"] = sender message["To"] = receiver message["Subject"] = subject message.attach(MIMEText(text)) # 添加附件 with open(attachment_path, "rb") as attachment_file: attachment = MIMEText(attachment_file.read()) attachment.add_header("Content-Disposition", "attachment", filename="attachment.txt") message.attach(attachment) # 发送邮件并检查是否发送成功 try: server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login(sender, "your_password") server.sendmail(sender, receiver, message.as_string()) print("Email sent successfully!") server.quit() except smtplib.SMTPException: print("Error: unable to send email") # 如果发送成功,打开附件 if "Email sent successfully!" in str(print()): with open(attachment_path, "r") as attachment_file: attachment_content = attachment_file.read() print(attachment_content) ``` 需要注意以下几点: 1. 在定义邮件对象时,使用`MIMEMultipart`对象可以添加多个文本附件;使用`MIMEText`对象可以添加文本。 2. 添加附件时需要打开附件文件,读取其内容并使用`MIMEText`对象添加到邮件信息中,同时需要添加`"Content-Disposition"`头部,告诉邮件客户端该文件是一个附件。 3. 发送邮件时需要连接到邮件服务器、进行身份验证并调用`sendmail`方法发送邮件,若出现异常则说明发送失败。 4. 在检测邮件发送成功后,可以打开附件文件并读取其内容
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值