Python发送邮件

#前言
这是新开账号后的第一篇文章,这个博客主要会记录工作、学习中遇到的一些问题,便于以后回顾。
#Python
关于Python,断断续续写了一些简易的工具代替需要重复操作的工作。
#Python发送邮件
该程序功能很简单:实现自动填写邮件并添加附件发送到指定的邮箱。

所用到的库:

import smtplib
from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import  make_header
import datetime

自动填写时间:

#date_process sample:2019年12月5日
def date_process():
    yestime = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%y{y}%m{m}%d{d}").format(y='年',m='月',d='日')
    return yestime
def date_process1():
    yestime = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%m%d")
    return yestime

发送和接收的定义:

# sender
sender = '*********'
user = '********'
password = '********'

#receiver
zs_receiver = ['**********']#主送
cs_receiver=["**********"] #抄送
receiver=zs_receiver+cs_receiver

附件调用处理:

path="D:/工作路径/注册用户数{x}.xls".format(x=DATE1)
send_file=open(path,'rb').read()
att=MIMEText(send_file,'base64','utf-8')                     
att["Content-Type"]='application/octet-stream'
att["Content-Disposition"] = 'attachment;filename= "%s"'% make_header([("注册用户数{x}.xls".format(x=DATE1), 'UTF-8')]).encode('UTF-8')#处理附件名乱码

正文、标题发送接收等:

msgRoot=MIMEMultipart()
msgRoot.attach(MIMEText(content, 'html', 'utf-8'))#content为邮件正文内容
msgRoot['subject']=subject  #mail title
msgRoot['From']=sender
msgRoot['To'] = ','.join(zs_receiver)
msgRoot['Cs']=','.join(cs_receiver)
msgRoot.attach(att)  

最后是发送邮件:

print("Start send email...")
def send_mail():
        try:
            smtp = smtplib.SMTP(smtpserver, 587)
            smtp.ehlo()
            smtp.starttls()
            smtp.login(user, password)
            smtp.sendmail(sender, receiver, msgRoot.as_string())  # 发送邮件
            smtp.quit()
        except Exception as error:
             print (error)
send_mail()
print("Send success")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值