使用Python 3发邮件

示例一:(使用yagmail模块)

直接使用别人封装好的第三方库:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/6/5 21:42
# @Author  : zhdya
# @File    : demon.py

import yagmail

args = {

    "user": "[email protected]",
    "password": "xxxxx",
    "host": "smtp.163.com",
    "port": "465"
}

yagmail.SMTP(**args)

emailList =  ['[email protected]','[email protected]']

email = yagmail.SMTP(**args)
email.send(to=emailList, subject="这是主题", contents="这是内容。。", cc="[email protected]", attachments="Server.py")

参数:

User  用户民
Password 用户密码,很多情况需要使用授权码
Host   smtp的地址
Port    默认使用ssl协议,默认是465端口
To   收件人
Subject     主题
Contents    消息内容
Attachments   附件
Cc  抄送人

实例二、

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/6/6 22:23
# @Author  : zhdya
# @File    : mmail2.py

import email.mime.multipart
import email.mime.text
import smtplib

msg = email.mime.multipart.MIMEMultipart()
msg['from'] = '[email protected]'
msg['to'] = '[email protected]'
msg['subject'] = 'I like Python'

context = '''Now the time is 20180606, I already learning Python from three month, during that time, I found a way which can let me learning fast...'''
text = email.mime.text.MIMEText(_text=context, _subtype="html")
msg.attach(text)

mmail = smtplib.SMTP_SSL()
mmail.connect("smtp.163.com", 465)
mmail.login("[email protected]", "xxxxxxx")
mmail.sendmail(from_addr='[email protected]', to_addrs='[email protected]', msg = msg.as_string())
mmail.close()

通过python发邮件步骤: 前提是:开通了第三方授权,可以使用smtp服务:

  1. 创建一个smtp对象
  2. 连接smp服务器,默认端口都是25
  3. 登录自己邮箱账号,
  4. 调用发送消息函数,参数:发件人,收件人,消息内容
  5. 关闭连接
mmail = smtplib.SMTP_SSL()
mmail.connect("smtp.163.com", 465)
mmail.login("[email protected]", "xxxxxxx")
mmail.sendmail(from_addr='[email protected]', to_addrs='[email protected]', msg = msg.as_string())
mmail.close()

创建一个消息对象:

msg = email.mime.multipart.MIMEMultipart()
msg['from'] = '[email protected]'
msg['to'] = '[email protected]'
msg['subject'] = 'I like Python'

分别指明邮件的发件人,收件, 只代表显示的问题。

消息内容:

定义一个字符串,来表示你得消息内容:

context = '''Now the time is 20180606, I already learning Python from three month, during that time, I found a way which can let me learning fast...'''

_subtype这个参数就决定了,你是以html解析的形式去发送,还是以text的形式去发送。

最终的效果:

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励