我們常常會用到一些發(fā)送郵件的功能,,比如有人提交了應(yīng)聘的表單,可以向HR的郵箱發(fā)郵件,,這樣,HR不看網(wǎng)站就可以知道有人在網(wǎng)站上提交了應(yīng)聘信息,。1. 配置相關(guān)參數(shù)如果用的是 阿里云的企業(yè)郵箱,,則類似于下面: 在 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]' DEFAULT_FROM_EMAIL 還可以寫成這樣: DEFAULT_FROM_EMAIL = 'tuweizhong <[email protected]>' 這樣別人收到的郵件中就會有你設(shè)定的名稱,如下圖: 下面是一些常用的郵箱: 其它郵箱參數(shù)可能登陸郵箱看尋找?guī)椭畔?,也可以嘗試在搜索引擎中搜索:"SMTP 郵箱名稱",,比如:"163 SMTP" 進行查找。 2. 發(fā)送郵件:2.1 官網(wǎng)的一個例子: from django.core.mail import send_mail send_mail('Subject here', 'Here is the message.', '[email protected]', ['[email protected]'], fail_silently=False) 2.2 一次性發(fā)送多個郵件: 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 每次發(fā)郵件都會建立一個連接,,發(fā)多封郵件時建立多個連接,。而 send_mass_mail 是建立單個連接發(fā)送多封郵件,所以一次性發(fā)送多封郵件時 send_mass_mail 要優(yōu)于 send_mail,。 2.3 如果我們想在郵件中添加附件,,發(fā)送 html 格式的內(nèi)容 from django.conf import settings from django.core.mail import EmailMultiAlternatives from_email = settings.DEFAULT_FROM_EMAIL # subject 主題 content 內(nèi)容 to_addr 是一個列表,發(fā)送給哪些人 msg = EmailMultiAlternatives(subject, content, from_email, [to_addr]) msg.content_subtype = "html" # 添加附件(可選) msg.attach_file('./twz.pdf') # 發(fā)送 msg.send() 上面的做法可能有一些風(fēng)險,,除非你確信你的接收者都可以閱讀 html 格式的 郵件,。 為安全起見,你可以弄兩個版本,,一個純文本(text/plain)的為默認的,,另外再提供一個 html 版本的(好像好多國外發(fā)的郵件都是純文本的) from __future__ import unicode_literals from django.conf import settings from django.core.mail import EmailMultiAlternatives subject = '來自自強學(xué)堂的問候' 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() |
|