首页 > 编程语言 >Python 发送邮件

Python 发送邮件

时间:2023-05-31 14:45:03浏览次数:39  
标签:Python self list send 发送 user message email 邮件

Python 发送邮件

1、案例一 (发送普通邮件)

import smtplib
from email.mime.text import MIMEText


# 发送普通邮件
# POP3 服务器地址:pop.qq.com
# SMTP 服务器地址:smtp.qq.com

class SendEmail:
    def __init__(self):
        # 发送邮件的用户
        self.send_user = '[email protected]'
        # SMTP 服务器地址:smtp.qq.com
        self.email_host = 'smtp.qq.com'
        # 服务器端口 465
        self.email_port = 465
        # 开启POP3/SMTP服务,在第三方客户端登录时,生成的授权码
        self.password = 'xxxxxxxxx'

    def send_email(self, title, data, user_list):
        try:
            message = MIMEText(data, _subtype='plain', _charset='utf-8')
            message['Subject'] = title
            message['From'] = self.send_user
            message['To'] = ";".join(user_list)
            server = smtplib.SMTP_SSL()
            server.connect(self.email_host, self.email_port)
            server.login(self.send_user, self.password)
            server.sendmail(self.send_user, user_list, message.as_string())
            server.close()
            print("发送邮件成功,请查收")
        except Exception as e:
            print("发送邮件失败,报错信息:", e)


if __name__ == '__main__':
    user_list = ["[email protected]"]
    title = "邮件标题"
    data = "邮件内容"
    send = SendEmail()
    send.send_email(title, data, user_list)

2、案例二 (发送带附件的邮件)

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


# 发送带附件的邮件
# POP3 服务器地址:pop.qq.com
# SMTP 服务器地址:smtp.qq.com

class SendEmail:
    def __init__(self):
        # 发送邮件的用户
        self.send_user = '[email protected]'
        # SMTP 服务器地址:smtp.qq.com
        self.email_host = 'smtp.qq.com'
        # 服务器端口 465
        self.email_port = 465
        # 开启POP3/SMTP服务,在第三方客户端登录时,生成的授权码
        self.password = 'xxxxxxxxx'

    def send_email(self, title, data, file_path_list, user_list):
        try:
            # 创建一个带附件的实例
            message = MIMEMultipart()
            message.attach(MIMEText(data, 'plain', 'utf-8'))
            message['Subject'] = title
            message['From'] = self.send_user
            message['To'] = ";".join(user_list)
            for file_path in file_path_list:
                # 构造附件
                attrs = MIMEText(open(file_path, 'rb').read(), 'base64', 'utf-8')
                attrs["Content-Type"] = 'application/octet-stream'
                # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
                attrs["Content-Disposition"] = 'attachment; filename={}'.format(str(file_path).split('/')[-1])
                message.attach(attrs)
            server = smtplib.SMTP_SSL()
            server.connect(self.email_host, self.email_port)
            server.login(self.send_user, self.password)
            server.sendmail(self.send_user, user_list, message.as_string())
            server.close()
            print("发送邮件成功,请查收")
        except Exception as e:
            print("发送邮件失败,报错信息:", e)


if __name__ == '__main__':
    user_list = ["[email protected]"]
    title = "邮件标题"
    data = "邮件内容"
    file_path_list = ['demo.jpg']
    send = SendEmail()
    send.send_email(title, data, file_path_list, user_list)

3、案例三 (发送一个HTML片段)

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


# 发送一个HTML片段
# POP3 服务器地址:pop.qq.com
# SMTP 服务器地址:smtp.qq.com

class SendEmail:
    def __init__(self):
        # 发送邮件的用户
        self.send_user = '[email protected]'
        # SMTP 服务器地址:smtp.qq.com
        self.email_host = 'smtp.qq.com'
        # 服务器端口 465
        self.email_port = 465
        # 开启POP3/SMTP服务,在第三方客户端登录时,生成的授权码
        self.password = 'xxxxxxxxx'

    def send_email(self, title, data, user_list):
        try:
            message = MIMEMultipart('related')
            content = MIMEText(data, 'html', 'utf-8')
            message.attach(content)
            message['Subject'] = title
            message['From'] = self.send_user
            message['To'] = ";".join(user_list)
            file = open("demo.jpg", "rb")
            img_data = file.read()
            file.close()
            img = MIMEImage(img_data)
            img.add_header('Content-ID', 'image')
            message.attach(img)
            server = smtplib.SMTP_SSL()
            server.connect(self.email_host, self.email_port)
            server.login(self.send_user, self.password)
            server.sendmail(self.send_user, user_list, message.as_string())
            server.close()
            print("发送邮件成功,请查收")
        except Exception as e:
            print("发送邮件失败,报错信息:", e)


if __name__ == '__main__':
    user_list = ["[email protected]"]
    title = "邮件标题"
    data = """
        <p>全是BUG</p>
        <p><a href="https://www.cnblogs.com/xingxingnbsp/">菜鸟程序员博客</a></p>
        <p>图片演示:</p>
        <p><img src="cid:image"></p>
    """
    send = SendEmail()
    send.send_email(title, data, user_list)

标签:Python,self,list,send,发送,user,message,email,邮件
From: https://www.cnblogs.com/xingxingnbsp/p/17446028.html

相关文章

  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-2-playwright的API及其他知识
    1.简介上一篇宏哥已经将Python+Playwright的环境搭建好了,而且也简单的演示了一下三款浏览器的启动和关闭,是不是很简单啊。今天主要是把一篇的中的代码进行一次详细的注释,然后说一下playwright的API和其他相关知识点。那么首先将上一篇中的代码进行一下详细的解释。2.代码解释2.......
  • Python 函数
    函数返回多个返回值defmultiple_return_value():importdatetimed=datetime.date.today()val_1='年份为:{}'.format(d.year)val_2='月份为:{}'.format(d.month)returnval_1,val_2#只需在return关键字后跟多个值(依次用逗号分隔)val=mult......
  • 无需发件箱的邮件群发软件
    奇石软件对于邮件营销工具一直非常关注,因为在获客成本不断飙升的今天,邮件引流获客成本低廉的优势凸显。最近奇石软件研发了一款邮件自动群发软件,本软件不同于常见的邮件群发软件,最主要的特点是【自动注册发件箱】,使用者无需准备大量发件箱,仅准备目标收件人列表即可。下面详细介......
  • python 中 re.match和re.search()函数
     两者都返回首次匹配字符串的索引,re.match函数只从头开始匹配,re.search函数不限制只从头开始匹配。001、re.match函数[root@PC1test2]#python3Python3.10.9(main,Mar12023,18:23:06)[GCC11.2.0]onlinuxType"help","copyright","credits"or"license"......
  • 无需发件箱的邮件发送软件
    奇石软件对于邮件营销工具一直非常关注,因为在获客成本不断飙升的今天,邮件引流获客成本低廉的优势凸显。最近奇石软件研发了一款邮件自动发送软件,本软件不同于常见的邮件软件,最主要的特点是【自动注册发件箱】,使用者无需准备大量发件箱,仅准备目标收件人列表即可。下面详细介绍一下:相......
  • python 视频拆分成帧,帧合成视频
    参考python将视频切分成帧&&帧合成视频,下面的代码来自这篇博客。#====================视频拆分成帧===================================importcv2defvideo2frame(videos_path,frames_save_path,time_interval):''':paramvideos_path:视频的存放路径:par......
  • 果然python是直接可以使用requests去请求https站点的,意味着一般的扫描工具可以直接扫
    #coding:utf-8importrequests#请求地址#url="https://www.qlchat.com"url="https://www.baidu.com"headers={'user-agent':'Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chro......
  • python 从bulkblacklist信誉查询网站提交查询
    importurllibimporturllib2#importwebbrowserimportreimportsocketdefis_domain_in_black_list(domain,ip):try_time=3url="http://www.bulkblacklist.com/"foriinrange(try_time):try:data=......
  • python avro 数据格式使用demo
    {"name":"UEProcedures","type":"record","fields":[{"name":"imsi","type":"string"},{"name":"time_at","type":&quo......
  • 【Python-Scripts】自动删除Jenkins任务构建历史记录
    任务背景: Jenkins构建历史记录很多,占用服务器磁盘空间较大,根据开发需求定期删除历史记录。 1#!/usr/bin/envpython2#-*-coding:utf-8-*-345importdatetime6importjenkins7importtime8fromjenkinsapi.jenkinsimportJenkins91011def......