Send mail django project

Copyright: bloggers without consent, is prohibited reprint. Thank you! https://blog.csdn.net/cp_123321/article/details/86513130

First write your own django project directory as follows

1. Configure settings.py file

# 将邮件打印在命令行窗口中
# EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"  # qq
# 邮件主机, 默认是localhost, 此处使用的是qq邮箱, qq邮箱使用的是smtp
EMAIL_HOST = "smtp.qq.com"
# SMTP服务端口, 默认25
EMAIL_POST = 25
# SMTP 服务器的用户名
EMAIL_HOST_USER = "[email protected]"
EMAIL_HOST_PASSWORD = "qq邮箱授权码"
# 是否使用TLS进行连接(TLS一种加密方式)
EMAIL_USE_TLS = True

2. Create a new file in the app project in forms.py

# Form 用于生成标准的表单
# ModelForm 用于从模型中生成表单
from django import forms


class EmailPostForm(forms.Form):
    # charfield 会被渲染成<input type="text">
    name = forms.CharField(max_length=25)
    email = forms.EmailField()
    to = forms.EmailField()
    # required=false  可选填  widget 参数决定该字段被渲染成的html元素类型 Textarea <textarea>
    content = forms.CharField(required=False, widget=forms.Textarea)

3. views.py write a file sharing function view article

from django.shortcuts import render, get_object_or_404  # get_object_or_404 如果匹配到,返回数据, 匹配不到返回404
from django.core.mail import send_mail
# 导入的这两个模块是自己写好的,
from blog.models import Post
from blog.forms import EmailPostForm


def post_share(request, post_id):
    """
    分享文章
    :param request:
    :param post_id:
    :return:
    """
    post = get_object_or_404(Post, id=post_id, status="published")
    sent = False  # sent 是否已发送(自定义),
    if request.method == "POST":
        # 表单被提交
        form = EmailPostForm(request.POST)
        if form.is_valid():  # 调用表单的is_valid方法,验证表单数据(验证表单中所有的数据是否有效),如果有任意字段未通过, 此时可以在form.errors属性中查看错误信息
            # 如果表单验证失败, form.cleaned_data只会包含通过验证的数据
            cd = form.cleaned_data  # 取出表单数据,字典
            # 发送邮件
            # build_absolute_uri 生成完整的url
            post_url = request.build_absolute_uri(post.get_absolute_url())
            subject = "{}({})分享给你{}".format(cd["name"], cd["email"], post.title)
            message = "阅读文章“{}”,文章的url:{}".format(post.title, post_url)
            send_mail(subject, message, '[email protected]', [cd["to"]])
            sent = True
    else:
        form = EmailPostForm()
    # 这里share.html会报错,写好第五步就可以了 
    return render(request, "share.html", {"form": form, "post": post, "sent": sent})

4. Add views.py in view of the function in the file urls.py

# 可以写在总路由里, 这里是app项目里创建的urls.py文件
urlpatterns = [
    
    path("<int:post_id>/share/", post_share, name="post_share")
]

5. Create a new file in a share.html templates folder

{% extends 'base.html' %}

{% block title %}
    分享一篇文章
{% endblock %}

{% block content %}
    {% if sent %}
        <h1>邮件发送成功!</h1>
        <p>
{#        form.cleaned_data 返回的是字典, 这里只能使用.取值 #}
            "{{ post.title }}" 已经成功发送到{{ form.cleaned_data.to }}
        </p>
    {% else %}
        <h1>通过邮件分享"{{ post.title }}"</h1>
        <form action="" method="post">
            {{ form.as_p }}
            {% csrf_token %}  {# 隐藏一个input标签,加密参数 #}
            <input type="submit" value="发送邮件">

        </form>
    {% endif %}

{% endblock %}

After completion of the project, share.html returned the following pages,

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/cp_123321/article/details/86513130