python 发送邮件给多人

python发送邮件相信很多python使用者都会,这里介绍针对发给多个收件人的心得:

关键点1:收件人邮箱msg_to=['[email protected]','[email protected]','[email protected]'],以列表的方式给出。

关键点2:msg['To'] =','.join(msg_to)。

关键点3:s.sendmail(msg_from, msg['To'].split(','), msg.as_string())

至于join()和split()大家可以看文档明白含义用法,处理好这三个关键点就可以成功利用python发送邮件给多人了。

代码
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import time
import pymysql


my_sender = '[email protected]'  # 发件人邮箱账号
my_pass = 'tiwypblkspxqbdfi'  # 发件人邮箱密码
my_user = ["[email protected]","[email protected]","[email protected]","[email protected]","[email protected]"] # 收件人邮箱账号

class Config:
    USERNAME = 'root'
    PASSWORD = '*****'
    HOSTNAME = '10.24.151.7'
    DATABASE = '***'


def mail():
    ret = True

    now_time = time.localtime(time.time() - 86400)
    day_time = int(time.mktime(time.strptime(time.strftime('%Y-%m-%d 00:00:00', now_time), '%Y-%m-%d %H:%M:%S')))

    print("开始执行..")
    db = pymysql.connect(
        Config.HOSTNAME,
        Config.USERNAME,
        Config.PASSWORD,
        Config.DATABASE,
        charset='utf8')
    cursor = db.cursor()
    print("数据库连接完毕 ")
    try:

        sql_one = "SELECT SUM(CAST(fee AS DECIMAL(10,2))) as fee_one FROM `alipay_order`WHERE payment_state=1 AND payment_time BETWEEN %s and %s"
        cursor.execute(sql_one, (day_time, day_time + 86400))
        print("支付宝生活号-数据库查询完毕 sql: {}, payment_time {} {}".format(sql_one, day_time, day_time + 86400))
        data_one = cursor.fetchall()
        _one = None
        for a in data_one:
            _one = a[0]
        fee_one = _one

        sql_two = 'select SUM(CAST(fee/100 AS DECIMAL(10,2))) as fee_two FROM alipay_b_order where payment_time BETWEEN %s and %s and state=1 AND bus_id in ("7119","7139","7150","7152","8850","7590")'
        cursor.execute(sql_two, (day_time, day_time + 86400))
        print("支付宝小程序-数据库查询完毕 sql: {}, payment_time {} {}".format(sql_two, day_time, day_time + 86400))
        data_two = cursor.fetchall()
        _two = None
        for b in data_two:
            _two = b[0]
        fee_two = _two

        sql_three = 'SELECT SUM(CAST(fee AS DECIMAL(10,2))) as fee_three FROM wechat_applet_order WHERE payment_state=1 AND payment_time BETWEEN %s and %s AND app_id in ("wxae06cebe2e0f9042","wx303e650f9b81ba59","wx5dd0637d33d1b00d","wxf819edfc37816c77","wxc22626c10c142ab9","wxb6c9cbf839ed8be4","wx4a53367365194b99","wx507a3308b839e8fe")'
        cursor.execute(sql_three, (day_time, day_time + 86400))
        print("微信小程序-数据库查询完毕 sql: {}, payment_time {} {}".format(sql_three, day_time, day_time + 86400))
        data_three = cursor.fetchall()
        _three = None
        for c in data_three:
            _three = c[0]
        fee_three = _three

        amount = fee_one + fee_two + fee_three

        mail_msg = '''
           
产品线 电子照金额 钱包支付金额 充值金额 已标电子照退款
线下团队 {0}元 0元 0元 0元
''' mail_msg = mail_msg.format(amount) msg = MIMEText(mail_msg, 'html', 'utf-8') msg['From'] = formataddr(["Thomas_tang", my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 msg['To'] = ','.join(my_user) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 import datetime today = datetime.date.today() today = str(today).replace("-", "") msg['Subject'] = "线下团队{}电子照金额总计".format(today) # 邮件的主题,也可以说是标题 server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是465 server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码 server.sendmail(my_sender, msg['To'].split(','), msg.as_string().encode("utf-8")) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件 server.quit() # 关闭连接 except Exception as e: # 如果 try 中的语句没有执行,则会执行下面的 ret=False ret = False return ret finally: cursor.close() db.close() if __name__ == '__main__': ret = mail() if ret: print("邮件发送成功") else: print("邮件发送失败")

你可能感兴趣的:(python 发送邮件给多人)