1. 配置相关参数
如果用的是 阿里云的企业邮箱,则类似于下面:
在 settings.py 的最后面加上这些
EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = False
EMAIL_HOST='smtp.163.com'
EMAIL_PORT='25'
EMAIL_HOST_USER='2222@163.com'
EMAIL_HOST_PASSWORD='**' 这里密码不是邮箱密码,是STMP申请密码,在邮箱里面可以设置,开通就可以设置密码
DEFAULT_FROM_EMAIL='2222@163.com'
2. 发送邮件:
2.1 官网的一个例子:(试过,不行)
1
2
3
4
|
from django.core.mail import send_mail
send_mail( 'Subject here' , 'Here is the message.' , 'from@example.com' ,
[ 'to@example.com' ], fail_silently = False )
|
1
2
3
4
5
6
7
8
|
from django.core.mail import send_mass_mail
message1 = ( 'Subject here' , 'Here is the message' , 'from@example.com' , [ 'first@example.com' , 'other@example.com' ])
message2 = ( 'Another Subject' , 'Here is another message' , 'from@example.com' , [ 'second@test.com' ])
send_mass_mail((message1, message2), fail_silently = False )
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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() |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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, [to@youemail.com])
msg.attach_alternative(html_content, "text/html" )
msg.send() |
上面代码打在app的views文件中,然后在project的urls中打下面的:
url(r'^$',emailapp_views.sent)运行manage.py runserver 2000 浏览器打开才可以发送,如果直接运行views会一直提示电脑没有连接成功