在本文中,我们将学习如何在Django项目中设置电子邮件。 Django使发送电子邮件变得方便,并提供了满足我们需求的各种方法。
在我们开始之前,我们必须在settings.py
文件中设置电子邮件设置。
1 2 3 4 5 |
EMAIL_HOST='smtp.sendgrid.net' EMAIL_HOST_USER='username' EMAIL_HOST_PASSWORD='password' EMAIL_PORT = 587 EMAIL_USE_TLS = True |
在settings.py文件中,我使用了EMAIL_HOST =’smtp.sendgrid.net’,也可以使用任何其他smtp主机,例如google smtp或任何其他主机。
我们已经创建了一个名为test_email的应用程序,并且已从该应用程序导入了视图,并且不要忘记在已安装的应用程序中包含test_email。
在test_email / urls.py中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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 settings from 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()函数,该函数接受以下参数。
使用:
1 2 3 |
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中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import os from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.template.loader import get_template,render_to_string # django email module from 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 = 'fromemail@example.com' to_email = ['toemail1@example.com','toemail2@example.com'] # 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的模板内容。
使用:
1 |
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”中创建模板。
1 2 3 |
<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中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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 = 'fromemail@example.com' to_email = ['toemail@example.com'] # 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中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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 = 'fromemail@example.com' to_email = ['toemail@example.com'] 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执行后关闭一次连接。
用法:
1 |
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中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
def bulk_email(request,*args,**kwargs): ctx_list = [ { 'username' : 'Alen1234', 'first_name':'Alen', 'last_name':'Jake', 'email':'toemail@example.com', 'subject':'email subject', 'msg':'This is the email msg' }, { 'username' : 'Tim34', 'first_name':'TIm', 'last_name':'Crook', 'email':'toemail@example.com', 'subject':'email subject', 'msg':'This is the email msg' }, ] from_email='fromemail@example.com' 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) |
总结:
我们到了这篇文章的结尾。 希望我们回答了您有关如何使用Django发送电子邮件和附件的问题。