qiyesafe.com

(原创)python发送邮件

这段时间一直在学习flask框架,看到flask扩展中有一个mail插件,所以今天就给大家演示如果发邮件。

      首先我注册了一个163邮箱,需要开启smtp功能,因为咱们python发送邮件经过的是smtp.163.com(网易的电子邮件服务器)。

注册好163邮箱,然后开启smtp功能,如下图所示:

 

开启的过程中需要绑定手机。   

    我最终实现的样子是这样的:

使用flask搭建了一个web服务器,然后做了一个网页,将收件人,主题,正文填好之后,点击发送,上面会显示发送结果。

 

下面是整个工程的结构:

templates是存放了两个html文件,pyMail实现所有的功能。接下来我列一下源代码,然后将发送部分的核心代码进行讲解。

 

base.html:
{% extends "bootstrap/base.html" %}

{% block title %}Flasky {% endblock %}

{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">七夜</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="http://blog.csdn.net/qiye_/">CSDN博客</a></li>
                <li><a href="http://www.cnblogs.com/qiyeboy/">博客园</a></li>
                <li><a href="/">公众号:qiye_python</a></li>
            </ul>
        </div>
    </div>
</div>
{% endblock %}

{% block content %}

<div class="container">
{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ message }}
</div>
{% endfor %}

{% block page_content %}{% endblock %}
</div>

{% endblock %}

  

index.html:

{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}首页 {% endblock %} {% block page_content %} <div class="page-header"> {% if name %} <h1> Hello,{{ name }}! </h1> {% else %} <h1>Hello,Stranger!</h1> {% endif %} </div> {{ wtf.quick_form(form) }} {% endblock %}
pyMail.py:


#coding:utf-8
from flask import Flask,render_template,session,url_for,redirect,flash
from flask.ext.mail import Mail, Message
from flask.ext.moment import Moment
from flask.ext.wtf import Form
from flask.ext.bootstrap import Bootstrap
from wtforms import StringField,SubmitField, TextAreaField
from wtforms.validators import Required, Email

import sys
reload(sys)
sys.setdefaultencoding('utf8')#设置系统默认编码为utf-8

'''
这个类描述了网页上的结构
'''
class MailForm(Form):
    receiver = StringField('收件人:',validators=[Required(),Email()])
    style = StringField('主题:',validators=[Required()])
    body = TextAreaField('正文:',validators=[Required()])
    submit = SubmitField('发送')

app = Flask(__name__)
app.config['SECRET_KEY'] = 'qiyeboy'
#下面是SMTP服务器配置
app.config['MAIL_SERVER'] = 'smtp.163.com' #电子邮件服务器的主机名或IP地址
app.config['MAIL_PORT'] = '25' #电子邮件服务器的端口
app.config['MAIL_USE_TLS'] = True #启用传输层安全
app.config['MAIL_USERNAME'] ='xxxxxx@163.com' #os.environ.get('MAIL_USERNAME') #邮件账户用户名
app.config['MAIL_PASSWORD'] = 'your password'#os.environ.get('MAIL_PASSWORD') #邮件账户的密码

mail = Mail(app)
bootstrap = Bootstrap(app)#进行网页渲染
moment = Moment(app)#时间

@app.route('/',methods=['GET','POST'])
def index():
    '''
       flask中的路由
    :return:
    '''
    mailForm = MailForm()#表单
    if mailForm.validate_on_submit():#表单提交成功的判断
        try:
            receiverName = mailForm.receiver.data #收件人文本框的内容
            styledata = mailForm.style.data#主题文本框的内容
            bodydata  = mailForm.body.data#正文文本框的内容
            msg = Message(styledata,sender='xxxxxx@163.com',recipients=[receiverName])#发件人,收件人
            msg.body = bodydata
            mail.send(msg)
            flash('邮件发送成功!')#提示信息
        except:
            flash('邮件发送失败!')

    return render_template('index.html',form=mailForm,name ='xxxxxx@163.com' )#渲染网页

if __name__ == '__main__':
    app.run(debug=True)

  

  我将代码中我的邮箱和密码都隐藏了,如果大家要试验的话,请换成自己的邮箱和密码,记住这个密码不是登录密码,而是开启smtp时输入的管理密码。
mail核心代码:
1.首先配置smtp服务器:
#下面是SMTP服务器配置

app.config['MAIL_SERVER'] = 'smtp.163.com' #电子邮件服务器的主机名或IP地址
app.config['MAIL_PORT'] = '25' #电子邮件服务器的端口
app.config['MAIL_USE_TLS'] = True #启用传输层安全
app.config['MAIL_USERNAME'] ='xxxxxx@163.com' #os.environ.get('MAIL_USERNAME') #邮件账户用户名
app.config['MAIL_PASSWORD'] = 'xxxxxx'#os.environ.get('MAIL_PASSWORD') #邮件账户的密码

2.发送邮件:

msg = Message(styledata,sender='xxxxxx@163.com',recipients=[receiverName])#发件人,收件人
msg.body = bodydata
mail.send(msg)

填好发件人,收件人,主题,正文,然后发送就OK了。

最后给大家看一下发送的演示图:

这时候我的qq邮箱已经收到了邮件:

今天的分享就到这里,七夜音乐台的开发正在进行中,敬请期待,记得打赏呦。

 

欢迎大家支持我的公众号:

 

posted @ 2016-03-19 15:20  七夜的故事  阅读(2262)  评论(0编辑  收藏  举报
qiyesafe.com