作用:借用该模块的内置参数,来实现发送邮件的过程
步骤:
导入包yagmail 之后, 通过mail = yagmail.smtp()实例化一个对象出来,需要传入的参数user=“发件人”,password=“授权码”, host=“smtp服务器”
获取授权码的位置(qq邮箱为例):
通过mail.send()模块发送邮件内容,参数:(to=“收件人”,subject=“邮件的主题”,contents=“邮件的正文”, attachments=“发送邮件的附件”)
作用: 该模块相当于Linux中的crontab,来实现定时完成发送邮件任务的过程
注:可以通过pip install yagmail 和pip install schedule 来安装这两个模块
import yagmail
def send_mail(sender='[email protected]', password=None, receivers=None,
subject='自动化发送邮件', contents=None, attaches=None, host='smtp.qq.com'):
"""
自动化发送邮件
:param sender:发件人
:param password: 验证码
:param receivers: 收件人
:param subject: 主题
:param contents: 内容
:param attaches: 附件
:param host: 服务器
:return: none
"""
try:
mail = yagmail.SMTP(user=sender, password=password, host=host)
mail.send(to=receivers, subject=subject, contents=contents, attachments=attaches)
except Exception as e:
print('邮件发送失败', e)
else:
print('邮件发送成功')
if __name__ == '__main__':
import schedule
password = '授权码'
receivers = '[email protected]'
contents = ["你的磁盘使用量已经高达90%
"]
attaches = ['picture.jpg']
schedule.every(2).seconds.do(send_mail, password=password,
receivers='[email protected]',
contents=contents,
attaches=attaches)
while True:
schedule.run_pending()