Myluzh Blog

Python邮件发送例子

发布时间: 2023-10-25 文章作者: myluzh 分类名称: Python 朗读文章


python邮件发送案例

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


class AutoEmail:
    def __init__(self):
        self.__sender_email = "support@itho.cn"
        self.__password = "qwer1234"

    def send_email(self, recipient_emails, subject, message):
        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = self.__sender_email
        
        # 检查recipient_emails是否是一个字符串。如果是字符串,则将其转换为包含单个收件人的列表
        if isinstance(recipient_emails, str):
            recipient_emails = [recipient_emails] 
        # 使用 join 方法将收件人邮箱地址连接起来
        msg['To'] = ", ".join(recipient_emails)

        msg.attach(MIMEText(message, 'plain'))
        try:
            server = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)
            server.login(self.__sender_email, self.__password)
            server.sendmail(self.__sender_email, recipient_emails, msg.as_string())
            server.quit()
            print("Email sent successfully! Recipients:", recipient_emails)
        except Exception as e:
            print("Failed to send email. Error:", str(e))


if __name__ == "__main__":
    AEL = AutoEmail()
    # 发送给多个收件人,传递一个列表进去
    AEL.send_email(["123@qq.com","456@qq.com"] ,'邮件标题', '多收件人测试内容')
    #发送给单个收件人
    #AEL.send_email("123@qq.com", '邮件标题', '单收件人测试内容')


标签: python email 邮件发送

发表评论