tiger-sms ChatGPT 账号/ChatGPT 代注册 OpenAI API 代充值

Python SMTP 发送邮件并添加附件教程

dajiaka OpenAI API key

之前老王介绍过《PHP 使用 SMTP 发送邮件教程(PEAR Mail 包)》,这次需求是用 Python 调用 SMTP 服务发送邮件,并且需要在邮件中添加附件(文本文件),本文分享下具体的代码。

一、准备工作

1、SMTP 邮箱

QQ 邮箱即可:《QQ 邮箱开启 SMTP 服务与获取 SMTP 账号信息(账号密码、服务器、端口)

2、添加包依赖

主要用到了 2 个 Python 自带的包,其中 smtplib 就是 Python SMTP 功能必用包:

import smtplib
from email.mime.text import MIMEText

二、源码分享

以下代码就是 Python3 调用 QQ 邮箱的 SMTP 发送邮件的源码,在发送的邮件内容中添加了一个附件:

def send_email(content, attach_file):
    msg_from = '8888888@qq.com'  # 发送方邮箱
    passwd = 'tjvoskdjsklkcaij'  # 填入发送方邮箱的授权码
    msg_to = '888888@gmail.com'  # 收件人邮箱

    subject = "The Subject"

    msg = MIMEMultipart()
    msg.attach(MIMEText(content, 'plain', 'utf-8'))
    msg['Subject'] = subject
    msg['From'] = msg_from
    msg['To'] = msg_to

    # 构造附件1,传送当前目录下的 attach_file 文件
    att1 = MIMEText(open(attach_file, 'rb').read(), 'base64', 'utf-8')
    att1["Content-Type"] = 'application/octet-stream'
    # 这里的 filename 可以任意写,写什么名字,邮件中显示什么名字
    att1["Content-Disposition"] = 'attachment; filename="diff.html"'
    msg.attach(att1)
    try:
        s = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 邮件服务器及端口号
        s.login(msg_from, passwd)
        s.sendmail(msg_from, msg_to, msg.as_string())
    except Exception as e:
        print(str(e))
赞(0)
关注我们
未经允许不得转载:老王博客 » Python SMTP 发送邮件并添加附件教程