python测试开发django-28.发送邮件

前言

django发邮件的功能很简单,只需简单的配置即可,发邮件的代码里面已经封装好了,调用send_mail()函数就可以了

send_mail()函数

先导入send_mail函数from django.core.mail import send_mail,进入源码里面看看具体函数对应的参数

  • subject: 邮件主题
  • message: 邮件内容
  • from_email: 发件人
  • recipient_list: 收件人,这是一个列表,可以有多个收件人
  • fail_silently: 是否报错,True的话表忽略异常
  • auth_user&auth_password:账号密码
  • connection: 表示这个的链接对象
  • html_message: send_mail方法独有,可以比较简单地实现一个html文本的传输
def send_mail(subject, message, from_email, recipient_list,
              fail_silently=False, auth_user=None, auth_password=None,
              connection=None, html_message=None):
    """
    Easy wrapper for sending a single message to a recipient list. All members
    of the recipient list will see the other recipients in the 'To' field.

    If auth_user is None, use the EMAIL_HOST_USER setting.
    If auth_password is None, use the EMAIL_HOST_PASSWORD setting.

    Note: The API for this method is frozen. New code wanting to extend the
    functionality should use the EmailMessage class directly.
    """
    connection = connection or get_connection(
        username=auth_user,
        password=auth_password,
        fail_silently=fail_silently,
    )
    mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, connection=connection)
    if html_message:
        mail.attach_alternative(html_message, 'text/html')

    return mail.send()

settings.py配置

发送邮件之前先在setting.py配置文件里面配置相关的邮箱信息,比如我这里是用的QQ邮箱,使用SSL加密方式,需要授权码登录
(至于如何获取授权码,可以在QQ邮箱设置里面开启,发送短信“配置邮件客户端”到1069070069)

# settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_USE_SSL = True        # SSL加密方式
EMAIL_HOST = 'smtp.qq.com'   # 发送邮件的邮箱 的 SMTP服务器,这里用了163邮箱
EMAIL_PORT = 465    # SMTP服务器端口
EMAIL_HOST_USER = '[email protected]'   # 发件人
EMAIL_HOST_PASSWORD = '授权码'   # 密码(这里使用的是授权码)
EMAIL_FROM = 'yoyo<[email protected]>'   # 邮件显示的发件人

如果是其它的企业邮箱,直接密码登录的话,使用TLS方式

EMAIL_USE_SSL = True
EMAIL_HOST = 'smtp.xx.com'  # 如果是其它企业邮箱
EMAIL_PORT = 25
EMAIL_HOST_USER = '[email protected]' # 帐号
EMAIL_HOST_PASSWORD = '**********'  # 密码
EMAIL_FROM = 'yoyo<[email protected]>'   # 邮件显示的发件人

EMAIL_USE_SSL 和 EMAIL_USE_TLS 是互斥的,只能有一个为 True。

views和urls.py

在views.py里面写过视图函数,调用发送邮件的功能

from django.http import HttpResponse
from django.core.mail import send_mail


def mail(request):
    send_mail('Subject here',             # 主题
              'Here is the message.',     # 正文
              '[email protected]',         # 发件人
              ['[email protected]'],       # 收件人
              fail_silently=False)
    return HttpResponse('邮件发送成功,收不到就去垃圾箱找找吧!')

urls.py写过访问地址
from django.conf.urls import url
from hello import views

urlpatterns = [
# 新增用户
url(r'^register/', views.register),
url(r'^login/', views.login),
url(r'^reset/', views.reset_psw),
url(r'^mail/', views.mail),]

```

浏览器上访问http://localhost:8000/mail/后,就能收到邮件了

猜你喜欢

转载自www.cnblogs.com/yoyoketang/p/10476989.html