Python自动发邮件
import datetime
import pymssql
import re
def get_gmv(sql):
ip = ''
user = ''
password = ''
database = ''
conn = pymssql.connect(ip, user, password, database)
cursor = conn.cursor()
cursor.execute(sql)
pdd_tmp = cursor.fetchone()
pdd = re.sub('[\[\(\)\],]', '', str(pdd_tmp)) # pdd = cursor.fetchall()
cursor.close()
conn.close()
return pdd
def send_email(
subject,
content_text,
mode="r",
sender_email="3029013611@qq.com", # 发件人
password="", # 授权码
receiver_list=["3029013611@qq.com", "1753147130@qq.com"], # 收件人
smtp_server=r"smtp.qq.com",
port=587
):
"""
:param subject: 标题
:param content_text:正文内容
:param mode: 附件格式
:param sender_email:
:param password:
:param receiver_list:
:param smtp_server:
:param port:
:return:
"""
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from os.path import basename as fn
for receiver_emails in receiver_list:
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_emails
context = ssl.create_default_context()
puretext = MIMEText(content_text)
msg.attach(puretext)
# csvpart = MIMEApplication(open(file_name, mode=mode).read())
# csvpart.add_header('Content-Disposition', 'attachment', filename=fn(file_name))
# msg.attach(csvpart)
with smtplib.SMTP(smtp_server, port) as server:
server.starttls(context=context)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_emails, msg=msg.as_string())
def main():
date = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%F")
subject = f"{date}日度业绩"
# sql = f"""..."""
# gmv = get_gmv(sql)
# content_text = f"{date}日业绩为{gmv}元。"
send_email(subject=subject, content_text="TEST")
if __name__ == '__main__':
main()