如何使用Django发送电子邮件和附件

admin 2020年8月16日17:01:55评论386 views字数 4578阅读15分15秒阅读模式
在本文中,我们将学习如何在Django项目中设置电子邮件。Django使发送电子邮件变得方便,并提供了满足我们需求的各种方法。
在我们开始之前,我们必须在settings.py文件中设置电子邮件设置。
EMAIL_HOST='smtp.sendgrid.net'EMAIL_HOST_USER='username'EMAIL_HOST_PASSWORD='password'EMAIL_PORT = 587EMAIL_USE_TLS = True
在settings.py文件中,我使用了EMAIL_HOST =’smtp.sendgrid.net’,也可以使用任何其他smtp主机,例如163或qq smtp或其它。
我们已经创建了一个名为test_email的应用程序,并且已从该应用程序导入了视图,并且不要忘记在已安装的应用程序中包含test_email。
在test_email / urls.py中
from django.urls import path, include from test_email.views import ( simple_email, email_with_template, email_with_attachment, email_with_custom_attachment_file_name, bulk_email, ) from django.conf import settingsfrom django.conf.urls.static import static app_name='test_email' urlpatterns = [    path('simple_email',simple_email, name='simple_email'),    path('email_with_template',email_with_template, name='email_with_template'),    path('email_with_attachment',email_with_attachment, name='email_with_attachment'),        path(        'email_with_custom_attachment_file_name',         email_with_custom_attachment_file_name,         name='email_with_custom_attachment_file_name'    ),        path('bulk_email',bulk_email, name='bulk_email'),]

发送简单的电子邮件
我们首先发送简单的电子邮件,因为我们将从django.core.mail模块中导入send_mail。
Django提供了方便的send_mail()函数,该函数接受以下参数。

使用:

send_mail(subject, message, from_email, recipient_list,     fail_silently=False, auth_user=None, auth_password=None,    connection=None, html_message=None)

send_mail参数
fail_silently:选项:True / False
设置为True时,错误将显示在视图中。
设置为False时,将忽略发生的错误。

auth_user:可选字段,用于接收电子邮件的经过身份验证的用户名。
auth_password:可选字段,用于接收电子邮件的经过身份验证的密码。
connection:可选字段,默认设置为默认设置。EMAIL_BACKEND,或者我们可以在settings.py文件中指定其他EMAIL_BACKEND。
html_message:接收消息html内容的可选参数。

在test_email / views.py中

import osfrom django.shortcuts import renderfrom django.http import HttpResponse, HttpResponseRedirectfrom django.conf import settingsfrom django.template.loader import get_template,render_to_string # django email modulefrom django.core.mail import send_mail,EmailMessage,send_mass_mail def simple_email(request,*args,**kwargs):    subject = 'This is email subject'     msg = 'This is the message of email'        from_email = '[email protected]'        to_email = ['[email protected]','[email protected]'] # can send email to multiple recipients        email_res = send_mail(subject,msg,from_email,to_email,fail_silently=False,)        return HttpResponse(email_res)

如果电子邮件发送成功,email_res将返回1。

使用模板发送电子邮件
Django提供了django.template.loader模块,该模块为我们提供了使用模板发送电子邮件的功能。

therender_to_string()是使用template_name,上下文作为参数的方法,该函数返回html的模板内容。

使用:

render_to_string(template_name, context=None, request=None, using=None)

ender_to_string()参数。

template_name:采用html模板的路径。
context:它是要传递到html模板的数据。
request:接受请求对象。
using:它是模板引擎。
创建模板
我们正在path =“ test_email / template / test_email / simple_email.html”中创建模板。

<h2>Welcome to Company Name</h2><p><strong>Dear {{first_name}} {{last_name}},</strong></p>    You have successfully registered  by user name <strong>"{{username}}"</strong>

在test_email / views.py中:

def email_with_template(request,*args,**kwargs):    subject = 'This is email subject'     ctx = {        'username' : 'Alen1234',        'first_name':'Alen',        'last_name':'Jake',    }        msg = render_to_string('test_email/simple_email.html',ctx)        from_email = '[email protected]'        to_email = ['[email protected]'] # can send email to multiple recipients        email_res = send_mail(subject, '', from_email, to_email, fail_silently=False, html_message=msg)        return HttpResponse(email_res)

使用附件发送电子邮件
django.core.mail提供EmailMessage是一个类,通过它我们可以通过电子邮件发送附件。

在test_email / views.py中。

def email_with_attachment(request,*args,**kwargs):    file_path = os.path.abspath('media/bg-2.jpg')        subject = 'This is email subject'        ctx = {        'username' : 'Alen1234',        'first_name':'Alen',        'last_name':'Jake',    }        msg = render_to_string('test_email/simple_email.html',ctx)        from_email = '[email protected]'        to_email = ['[email protected]']     mail = EmailMessage(        subject,        msg,        from_email,        to_email,    )        mail.content_subtype='html'     mail.attach_file(file_path)        email_res = mail.send()        return HttpResponse(email_res)

发送批量电子邮件
Django django.core.mail提供send_mass_mail()函数,该函数在其内部调用了类EmailMessage。但是send_mass_mail()保持连接打开,而send_mail执行后关闭一次连接。

用法:

send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None)

send_mass_mail()参数。
datatuple:采用多个元组,其中包括subject,from_email,to_email,msg。

在test_email / views.py中。

def bulk_email(request,*args,**kwargs):    ctx_list = [        {            'username' : 'Alen1234',            'first_name':'Alen',            'last_name':'Jake',            'email':'[email protected]',            'subject':'email subject',            'msg':'This is the email msg'        },        {            'username' : 'Tim34',            'first_name':'TIm',            'last_name':'Crook',            'email':'[email protected]',            'subject':'email subject',            'msg':'This is the email msg'        },    ]     from_email='[email protected]'    email_tuple = tuple()     for i in ctx_list:        email_tuple=email_tuple+((        i['subject'],         i['msg'],        from_email,        [i['email']]),)     email_res = send_mass_mail((email_tuple), fail_silently=False)     return HttpResponse(email_res)


完毕,希望对大家学习有帮助。

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2020年8月16日17:01:55
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   如何使用Django发送电子邮件和附件http://cn-sec.com/archives/91034.html

发表评论

匿名网友 填写信息