跳转至

python 邮件

import datetime
import locale
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.utils import formataddr

# 设置本地化信息为中文(中国)
locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S %A")

# 发送方和接收方的信息
sender_email = "uyme@qq.com"
password = "1111111111"

# 创建一个多部分消息对象
message = MIMEMultipart()

# 设置邮件的主题、发件人和收件人
receiver_email = "aooboo@88.com"
message["Subject"] = f"测试邮件{now}"
message['From'] = formataddr(('机器人-96', sender_email))
message['To'] = formataddr(('', receiver_email))


def add_attachment(message,file_name):

    # 添加附件
    with open(file_name, "rb") as attachment:
        att = MIMEApplication(attachment.read(), _subtype=file_name.split(".")[-1])
        att.add_header("Content-Disposition", "attachment", filename=file_name)
        message.attach(att)



def add_img(message,img_name,imageid):
    '''
    添加图片
    img_name 图片名称
    imageid 图片的ID ,用来在正文中引用
    '''

    with open(img_name, "rb") as f:
        img_data = f.read()
        img = MIMEImage(img_data)
        message.attach(img)
        img.add_header('Content-ID', f'<{imageid}>')
    return f"<img src='cid:{imageid}'>"


add_attachment(message,"ccc.py")
image1 = add_img(message,"20230410113916.png",'aadd')

# 在邮件正文中使用 <img> 标记引用图像
body = f'<h1>这是一张图片</h1>:<br><br><br>{image1}'

message.attach(MIMEText(body, 'html'))



# 发送邮件
with smtplib.SMTP("smtp.qq.com", 587) as smtp:
    smtp.starttls()
    smtp.login(sender_email, password)
    smtp.sendmail(sender_email, receiver_email, message.as_string())