Django 发送邮箱的代码
时间: 2023-06-12 11:03:09 浏览: 54
要在 Django 中发送电子邮件,需要在 settings.py 文件中配置电子邮件设置,如下所示:
```python
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com' # 邮箱服务器地址
EMAIL_PORT = 587 # 邮箱服务器端口
EMAIL_USE_TLS = True # 开启TLS安全连接
EMAIL_HOST_USER = 'your_email@gmail.com' # 发送邮件的邮箱账号
EMAIL_HOST_PASSWORD = 'your_email_password' # 发送邮件的邮箱密码
```
接下来,可以使用以下代码发送电子邮件:
```python
from django.core.mail import send_mail
send_mail(
'Subject here', # 邮件主题
'Here is the message.', # 邮件内容
'from@example.com', # 发件人
['to@example.com'], # 收件人列表
fail_silently=False, # 发送失败是否抛出异常
)
```
如果要发送带有 HTML 格式的邮件,可以使用以下代码:
```python
from django.core.mail import EmailMultiAlternatives
subject, from_email, to = 'subject', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
```
注意,如果使用 Gmail 发送电子邮件,需要在 Gmail 账户的设置中开启“允许 less secure apps 访问你的帐户”选项。