python smtp发送正文邮件 , 以及发送带有附件的邮件

1、smtp发送正文邮件

from email.header import Header
from email.mime.text import MIMEText
from smtplib import SMTP


def send_email(receivers, topic, msg, sender='[email protected]'):
    """
    :param receivers: 收件人列表
    :param topic:  邮件主题
    :param msg:  邮件内容
    :param sender: 邮件发送者
    :return:
    """
    for receiver in receivers:
        try:
            message = MIMEText(msg, 'plain', 'utf-8')
            message['From'] = Header(sender, 'utf-8')  # 发件人
            message['To'] = Header(receiver, 'utf-8')  # 收件人
            message['Subject'] = Header(topic, 'utf-8')
            smtper = SMTP('smtp.qq.com', 25)
            password = 'xxx'  # smtp服务的密码,非qq登录密码
            smtper.login(sender, password)
            smtper.sendmail(sender, receiver, message.as_string())
            print('邮件发至:%s, 成功……' % receiver)
        except Exception as err:
            print('邮件发至:%s, 失败……错误信息为:%s' % (receiver, err))
            continue


if __name__ == '__main__':
    receivers = ['[email protected]']
    topic = '邮件测试'
    msg = '邮件测试,请勿回复'
    send_email(receivers, topic, msg)

发送者邮箱,接受者邮箱需要自己定义,邮件主题和内容也需要自己定义好,receivers是一个列表,topic和msg均为字符串。

运行程序之前,应该确保发送者邮箱已经开启smtp服务

qq邮件为例开启smtp服务的步骤:

1、打开自己的邮箱:
这里写图片描述

2、点击“设置”:
这里写图片描述

3、在设置界面点击“账户”:
这里写图片描述

4、下拉界面,来到“POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务”:
这里写图片描述

5、开启服务“POP3/SMTP服务 ”,发送短信“配置邮箱……”,随后页面会返回一个密码,改密码就是程序中smtper.login(sender, password)中的密码。

2、发送带有附件的邮件

from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP


def send_email(receivers, topic, content, sender='xxx', password='xxx'):
    # 自己填好相关信息
    for receiver in receivers:
        try:
            msg = MIMEMultipart()
            msg['From'] = Header(sender, 'utf-8')  # 编辑邮件头
            msg['To'] = Header(receiver, 'utf-8')
            msg['Subject'] = Header(topic, 'utf-8')
            msg.attach(MIMEText(content, 'plain', 'utf-8'))  # 把正文附在邮件上

            with open('timg (15).jpg', 'rb') as f:
                mime = MIMEBase('image', 'png', filename='Hello.png')  # 创建表示附件的MIMEBase对象,重新命名为test.png
                mime.add_header('Content-Disposition', 'attachment', filename='test.png')
                mime.set_payload(f.read())  # 读取附件内容
                encoders.encode_base64(mime)  # 对附件Base64编码
                msg.attach(mime)  # 把附件附在邮件上
                server = SMTP('smtp.qq.com', 25)
                server.login(sender, password)
                server.sendmail(sender, receiver, msg.as_string())
                print('发送成功!')
        except Exception as error:
            print(error)
            continue


if __name__ == '__main__':
    receiver = ['xxx']
    topic = '邮件测试'
    content = '邮件测试,请勿回复'
    send_email(receiver, topic, content)

你可能感兴趣的:(python smtp发送正文邮件 , 以及发送带有附件的邮件)