1. 程式人生 > >46)django-發送郵件

46)django-發送郵件

false 備註 ont spa 查找 可選 有一個 lB 郵件

django已封裝好了郵件發送功能,可以直接調用發送模塊

1. 配置相關參數 如果用的是 阿裏雲的企業郵箱,則類似於下面: 在 settings.py 的最後面加上類似這些 EMAIL_BACKEND = django.core.mail.backends.smtp.EmailBackend EMAIL_USE_TLS = False EMAIL_HOST = smtp.tuweizhong.com EMAIL_PORT = 25 EMAIL_HOST_USER = [email protected] EMAIL_HOST_PASSWORD = xxxx DEFAULT_FROM_EMAIL
= [email protected] 或者 EMAIL_USE_SSL = True EMAIL_HOST = smtp.qq.com # 如果是 163 改成 smtp.163.com EMAIL_PORT = 465 EMAIL_HOST_USER = [email protected] # 帳號 EMAIL_HOST_PASSWORD = p@ssw0rd # 密碼 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_USE_SSL 和 EMAIL_USE_TLS 是互斥的,即只能有一個為 True。 DEFAULT_FROM_EMAIL 還可以寫成這樣:
1 DEFAULT_FROM_EMAIL = tuweizhong <[email protected]> 這樣別人收到的郵件中就會有你設定的名稱,如下圖: django_sendemail.png 下面是一些常用的郵箱: 163 郵箱 126 郵箱 QQ 郵箱 其它郵箱參數可能登陸郵箱看尋找幫助信息,也可以嘗試在搜索引擎中搜索:"SMTP 郵箱名稱",比如:"163 SMTP" 進行查找。 2. 發送郵件: 2.1 官網的一個例子: from django.core.mail import send_mail send_mail(Subject here
, Here is the message., [email protected], [[email protected]], fail_silently=False) 2.2 一次性發送多個郵件: from django.core.mail import send_mass_mail message1 = (Subject here, Here is the message, [email protected], [[email protected], [email protected]]) message2 = (Another Subject, Here is another message, [email protected], [[email protected]]) send_mass_mail((message1, message2), fail_silently=False) 備註:send_mail 每次發郵件都會建立一個連接,發多封郵件時建立多個連接。而 send_mass_mail 是建立單個連接發送多封郵件,所以一次性發送多封郵件時 send_mass_mail 要優於 send_mail。 2.3 如果我們想在郵件中添加附件,發送 html 格式的內容 from django.conf import settings from django.core.mail import EmailMultiAlternatives from_email = settings.DEFAULT_FROM_EMAIL # subject 主題 content 內容 to_addr 是一個列表,發送給哪些人 msg = EmailMultiAlternatives(subject, content, from_email, [to_addr]) msg.content_subtype = "html" # 添加附件(可選) msg.attach_file(./twz.pdf) # 發送 msg.send() 上面的做法可能有一些風險,除非你確信你的接收者都可以閱讀 html 格式的 郵件。 為安全起見,你可以弄兩個版本,一個純文本(text/plain)的為默認的,另外再提供一個 html 版本的(好像好多國外發的郵件都是純文本的) from __future__ import unicode_literals from django.conf import settings from django.core.mail import EmailMultiAlternatives subject = 來自自強學堂的問候 text_content = 這是一封重要的郵件. html_content = <p>這是一封<strong>重要的</strong>郵件.</p> msg = EmailMultiAlternatives(subject, text_content, from_email, [[email protected]]) msg.attach_alternative(html_content, "text/html") msg.send()

46)django-發送郵件