杨梅冲
每天在想什么呢?
要求:
发送一封简单的邮件 发送html格式的邮件 在邮件中带图片
发送邮件步骤:
1.登录邮件服务器
2.构造符合邮件协议规则的邮件内容
3.发送

python对SMTP支持有smtplib和email模块,email负责构造邮件,smtplib负责发送邮件
import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 登录邮件服务器
smtp_obj = smtplib.SMTP_SSL('smtp.exmail.qq.com', 465) # 发件人邮箱smtp服务器和端口
smtp_obj.login("ymc@qq.com", "password")  # 发件人邮件账号密码,password可以是授权码
smtp_obj.set_debuglevel(1) # 调试信息

 # 设置邮件头信息
 msg = MIMEText("Hello,email", "plain", "utf-8")
 msg["From"] = Header("来自xc的问候", "utf-8") # 发送者
 msg["To"] = Header("有缘人", "utf-8") #接收首
 msg["Subject"] = Header("xc的信", "utf-8")

 # 发送                              【发件人,收件人】
 smtp_obj.sendmail("ymc@qq.com", ["aa@qq.com", "xx@163.com"], msg.as_string())

二、发送工资条

处理excel信息表,批量给每个员工发工资条

举例

 

from email.mime.text import MIMEText

from openpyxl import load_workbook
import smtplib


# 加载excel文件,data_only将公式算出来
wb = load_workbook("salary.xlsx", data_only=True)
sheet = wb.active

# 登录
smtp_obj = smtplib.SMTP_SSL('smtp.exmail.qq.com', 465)
smtp_obj.login("ymc@qq.com", "password")

# 设置邮件内容

# 循环excel
count = 0
table_col_names = []
table_col_html = '<thead>' #表头
for row in sheet.iter_rows(min_row=1):
    count += 1
    if count == 1:
        for col in row:
            # table_col_names.append(col.value)
            table_col_html += f"<th>{col.value}</th>"
        table_col_html += "</thead>"
        continue
    else:
        row_text = "<tr>"
        for cell in row:
            print(cell.value, end=",")
            row_text += f"{cell.value}"

        name = row[2]
        staff_email = row[1].value
        print(name.value,staff_email)

# 表格格式
    mail_body_context = f"""
        <h3>{name.value},你好:</h3>
        <p>请查收2022年-01月工资条</p>
        <table border="1px solid black">
           {table_col_html}
           {row_text}
        </table>
    """
    msg_body = MIMEText(mail_body_context, "html", "utf-8")

    msg_body["From"] = Header("人事部", "utf-8")  # 发送者
    msg_body["To"] = Header("员工", "utf-8")  # 接收首
    msg_body["Subject"] = Header("1月工资", "utf-8")

    # 发邮件
    smtp_obj.sendmail("ymc@qq.com", [staff_email,],msg_body.as_string())
    print(f"成功发送供资料到{staff_email}-{name.value}...")

 

posted on 2024-05-27 14:41  杨梅冲  阅读(36)  评论(0编辑  收藏  举报