python測試開發django-28.發送郵件send_mail


前言

django發郵件的功能很簡單,只需簡單的配置即可,發郵件的代碼里面已經封裝好了,調用send_mail()函數就可以了
實現多個郵件發送可以用send_mass_mail()函數

send_mail()函數

先導入send_mail函數from django.core.mail import send_mail,進入源碼里面看看具體函數對應的參數
subject,message,from_email 和recipient_list 這四個參數是必須的。

  • subject: 字符串,郵件標題。
  • message: 字符串,郵件內容。
  • from_email: 字符串,發件郵箱。
  • recipient_list: list列表,列表中每個成員都是一個郵箱地址,而且每個收件人都會在 “收件人/To:” 欄看到出現在recipient_list 中的其他收件人。
  • fail_silently: (可選)布爾值。為False 時,send_mail 會拋出smtplib.SMTPException 異常。smtplib 文檔列出了所有可能的異常。這些異常都是 SMTPException 的子類。
  • auth_user:(可選)SMTP服務器的認證用戶名。沒提供該參數的情況下,Django會使用EMAIL_HOST_USER 配置項的設置。
  • auth_password:(可選)SMTP服務器的認證密碼,沒提供該參數的情況下,Django會使用EMAIL_HOST_PASSWORD 配置項的設置。
  • connection: (可選)發送郵件的后端。沒提供該參數的情況下,Django會使用默認后端的實例。
  • 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 = '283340479@qq.com'   # 發件人
EMAIL_HOST_PASSWORD = '授權碼'   # 密碼(這里使用的是授權碼)
EMAIL_FROM = 'yoyo<283340479@qq.com>'   # 郵件顯示的發件人

如果是其它的企業郵箱,直接密碼登錄的話,使用TLS方式

EMAIL_USE_SSL = True
EMAIL_HOST = 'smtp.xx.com'  # 如果是其它企業郵箱
EMAIL_PORT = 25
EMAIL_HOST_USER = 'xxx@xx.com' # 帳號
EMAIL_HOST_PASSWORD = '**********'  # 密碼
EMAIL_FROM = 'yoyo<xx@xx.com>'   # 郵件顯示的發件人

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.',     # 正文
              '283340479@qq.com',         # 發件人
              ['xxxxx@qq.com'],       # 收件人
              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/后,就能收到郵件了

前面講的send_mail()函數只能發送一個郵件,如果想實現發送多個郵件,可以用send_mass_mail()函數

send_mass_mail函數

先倒入from django.core.mail import send_mass_mail查看對應的源碼

def send_mass_mail(datatuple, fail_silently=False, auth_user=None,
                   auth_password=None, connection=None):
    """
     給定tuple數據類型(subject,message,from_email,recipient_list),發送每封郵件到每個收件人列表。 返回發送的電子郵件數量。

     如果from_email為None,請使用DEFAULT_FROM_EMAIL設置。
     如果設置了auth_user和auth_password,請使用它們登錄。
     如果auth_user為None,請使用EMAIL_HOST_USER設置。
     如果auth_password為None,請使用EMAIL_HOST_PASSWORD設置。

     注意:此方法的API已凍結。 想要擴展的新代碼功能應該直接使用EmailMessage類。
    """
    connection = connection or get_connection(
        username=auth_user,
        password=auth_password,
        fail_silently=fail_silently,
    )
    messages = [
        EmailMessage(subject, message, sender, recipient, connection=connection)
        for subject, message, sender, recipient in datatuple
    ]
    return connection.send_messages(messages)

從上面介紹可以看出,需傳元祖類型的數據,如果想實現更多的給你可以用EmailMessage類

發送多個郵件

多個郵件的配置信息放到一個元祖里面,傳給datatuple參數,代碼實現如下

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

# Create your views here.


def mass_mail(request):
    '''發送多個郵件'''
    message1 = ('Subject 1',
                'Here is the message',
                '2833404xx@qq.com',         # 發件人
                ['xxx@xx.com'])  # 收件人,多個收件人逗號隔開
    message2 = ('Another Subject2',
                'Here is another message',
                '2833404xx@qq.com',
                ['xxx@xx.com'])
    send_mass_mail((message1, message2),
                   fail_silently=False)
    return HttpResponse('郵件發送成功,收不到就去垃圾箱找找吧!')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM