2016年4月17日 星期日

[Django] 利用 Gmail 發送 email

由於專案上的功能,必須透過 Django 發送 email 給予前端使用者。不打算自行架設郵件伺服器的前提下,利用 Gmail 進行發送成為解決方案的首選!以下將介紹如何利用 Django + Gmail 發送郵件:

首先,對 Django settings 加入以下設定:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'YOUR GMAIL ACCOUNT'
EMAIL_HOST_PASSWORD = 'YOUR GMAIL PASSWORD'
EMAIL_USE_TLS = 'True'
EMAIL_POST = '587'


接著,就可以透過以下兩種不同程式寫法進行郵件的發送。

方法一:透過 send_mail() 發送

from django.core.mail import send_mail

send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False)


方法二:透過 EmailMessage 類別發送

from django.core.mail import EmailMessage

email = EmailMessage('Hello', 'Body goes here.', 'from@example', ['to@example.com', 'to2@example.com'], ['bcc@example.com'])

email.send()


就是這麼簡單即可透過 Django 發送 email 惹!