问题:如何通过Django发送电子邮件?

在我的中settings.py,我具有以下内容:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

# Host for sending e-mail.
EMAIL_HOST = 'localhost'

# Port for sending e-mail.
EMAIL_PORT = 1025

# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False

我的电子邮件代码:

from django.core.mail import EmailMessage
email = EmailMessage('Hello', 'World', to=['user@gmail.com'])
email.send()

当然,如果通过设置调试服务器python -m smtpd -n -c DebuggingServer localhost:1025,则可以在终端中看到该电子邮件。

但是,实际上我该如何将电子邮件发送到user@gmail.com而不是发送到调试服务器?

阅读您的答案后,让我弄明白一点:

  1. 您不能使用localhost(简单的ubuntu pc)发送电子邮件吗?

  2. 我以为在django 1.3中send_mail()已经过时了,EmailMessage.send()取而代之的是?

In my settings.py, I have the following:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

# Host for sending e-mail.
EMAIL_HOST = 'localhost'

# Port for sending e-mail.
EMAIL_PORT = 1025

# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False

My email code:

from django.core.mail import EmailMessage
email = EmailMessage('Hello', 'World', to=['user@gmail.com'])
email.send()

Of course, if I setup a debugging server via python -m smtpd -n -c DebuggingServer localhost:1025, I can see the email in my terminal.

However, how do I actually send the email not to the debugging server but to user@gmail.com?

After reading your answers, let me get something straight:

  1. Can’t you use localhost(simple ubuntu pc) to send e-mails?

  2. I thought in django 1.3 send_mail() is somewhat deprecated and EmailMessage.send() is used instead?


回答 0

将电子邮件发送到真实的SMTP服务器。如果您不想建立自己的公司,则可以找到可以为您经营公司的公司,例如Google自己。

Send the email to a real SMTP server. If you don’t want to set up your own then you can find companies that will run one for you, such as Google themselves.


回答 1

我将Gmail用作Django的SMTP服务器。比处理postfix或任何其他服务器容易得多。我不从事电子邮件服务器的管理。

在settings.py中:

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'me@gmail.com'
EMAIL_HOST_PASSWORD = 'password'

注意:默认情况下,2016年Gmail不再允许这样做。您可以使用Sendgrid之类的外部服务,也可以按照Google的本教程来降低安全性,但可以选择以下选项:https : //support.google.com/accounts/answer/6010255

I use Gmail as my SMTP server for Django. Much easier than dealing with postfix or whatever other server. I’m not in the business of managing email servers.

In settings.py:

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'me@gmail.com'
EMAIL_HOST_PASSWORD = 'password'

NOTE: In 2016 Gmail is not allowing this anymore by default. You can either use an external service like Sendgrid, or you can follow this tutorial from Google to reduce security but allow this option: https://support.google.com/accounts/answer/6010255


回答 2

  1. 创建一个项目: django-admin.py startproject gmail
  2. 使用以下代码编辑settings.py:

    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_USE_TLS = True
    EMAIL_HOST = 'smtp.gmail.com'
    EMAIL_HOST_USER = 'youremail@gmail.com'
    EMAIL_HOST_PASSWORD = 'email_password'
    EMAIL_PORT = 587
  3. 运行交互模式: python manage.py shell

  4. 导入EmailMessage模块:

    from django.core.mail import EmailMessage
  5. 发送电子邮件:

    email = EmailMessage('Subject', 'Body', to=['your@email.com'])
    email.send()

有关更多信息,请检查send_mail文档中的EmailMessage功能。

Gmail更新

另外,如果您在通过gmail发送电子邮件时遇到问题,请记住从Google 查看本指南

在您的Google帐户设置中,转到 Security > Account permissions > Access for less secure apps并启用此选项。

启用两步验证后,还要为您的gmail创建一个应用专用密码

然后,您应该在设置中使用应用专用密码。因此,更改以下行:

    EMAIL_HOST_PASSWORD = 'your_email_app_specific_password'

另外,如果您有兴趣发送HTML电子邮件,请检查此

  1. Create a project: django-admin.py startproject gmail
  2. Edit settings.py with code below:

    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_USE_TLS = True
    EMAIL_HOST = 'smtp.gmail.com'
    EMAIL_HOST_USER = 'youremail@gmail.com'
    EMAIL_HOST_PASSWORD = 'email_password'
    EMAIL_PORT = 587
    
  3. Run interactive mode: python manage.py shell

  4. Import the EmailMessage module:

    from django.core.mail import EmailMessage
    
  5. Send the email:

    email = EmailMessage('Subject', 'Body', to=['your@email.com'])
    email.send()
    

For more informations, check send_mail and EmailMessage features in documents.

UPDATE for Gmail

Also if you have problems sending email via gmail remember to check this guides from google.

In your Google account settings, go to Security > Account permissions > Access for less secure apps and enable this option.

Also create an App specific password for your gmail after you’ve turned on 2-step-verification for it.

Then you should use app specific password in settings. So change the following line:

    EMAIL_HOST_PASSWORD = 'your_email_app_specific_password'

Also if you’re interested to send HTML email, check this out.


回答 3

我的网站位于Godaddy,我在同一网站上注册了一封私人电子邮件。这些是对我有用的设置:

在settings.py中:

EMAIL_HOST = 'mail.domain.com'
EMAIL_HOST_USER = 'abc@domain.com'
EMAIL_HOST_PASSWORD = 'abcdef'
DEFAULT_FROM_EMAIL = 'abc@domain.com'
SERVER_EMAIL = 'abc@domain.com'
EMAIL_PORT = 25
EMAIL_USE_TLS = False

在外壳中:

from django.core.mail import EmailMessage
email = EmailMessage('Subject', 'Body', to=['def@domain.com'])
email.send()

然后我得到“ 1”作为O / P,即成功。而且我也收到了邮件。:)

  • domain.com是什么意思?

My site is hosted on Godaddy and I have a private email registered on the same. These are the settings which worked for me:

In settings.py:

EMAIL_HOST = 'mail.domain.com'
EMAIL_HOST_USER = 'abc@domain.com'
EMAIL_HOST_PASSWORD = 'abcdef'
DEFAULT_FROM_EMAIL = 'abc@domain.com'
SERVER_EMAIL = 'abc@domain.com'
EMAIL_PORT = 25
EMAIL_USE_TLS = False

In shell:

from django.core.mail import EmailMessage
email = EmailMessage('Subject', 'Body', to=['def@domain.com'])
email.send()

Then I got “1” as the O/P i.e. Success. And I received the mail too. :)

  • What is the meaning of domain.com?

回答 4

对于Django 1.7版,如果上述解决方案不起作用,请尝试以下操作

settings.py中添加

#For email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_HOST_USER = 'sender@gmail.com'

#Must generate specific password for your app in [gmail settings][1]
EMAIL_HOST_PASSWORD = 'app_specific_password'

EMAIL_PORT = 587

#This did the trick
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

最后一行完成了Django 1.7的技巧

For Django version 1.7, if above solutions dont work then try the following

in settings.py add

#For email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_HOST_USER = 'sender@gmail.com'

#Must generate specific password for your app in [gmail settings][1]
EMAIL_HOST_PASSWORD = 'app_specific_password'

EMAIL_PORT = 587

#This did the trick
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

The last line did the trick for django 1.7


回答 5

您需要使用smtp作为 settings.py中的后端

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

如果将后端用作控制台,则将在控制台中接收输出

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

还有下面的设置

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'urusername@gmail.com'
EMAIL_HOST_PASSWORD = 'password'

如果您为此使用gmail,请设置两步验证特定应用程序的密码,然后将该密码复制并粘贴到上面的EMAIL_HOST_PASSWORD值中。

You need to use smtp as backend in settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

If you use backend as console, you will receive output in console

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

And also below settings in addition

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'urusername@gmail.com'
EMAIL_HOST_PASSWORD = 'password'

If you are using gmail for this, setup 2-step verification and Application specific password and copy and paste that password in above EMAIL_HOST_PASSWORD value.


回答 6

我发现使用SendGrid是设置使用Django发送电子邮件的最简单方法。运作方式如下:

  1. 创建一个SendGrid帐户(并验证您的电子邮件)
  2. 将以下内容添加到您的settings.py EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = '<your sendgrid username>' EMAIL_HOST_PASSWORD = '<your sendgrid password>' EMAIL_PORT = 587 EMAIL_USE_TLS = True

一切准备就绪!

发送电子邮件:

from django.core.mail import send_mail
send_mail('<Your subject>', '<Your message>', 'from@example.com', ['to@example.com'])

如果您希望Django在出现500个内部服务器错误时向您发送电子邮件,请将以下内容添加到您的中settings.py

DEFAULT_FROM_EMAIL = 'your.email@example.com'
ADMINS = [('<Your name>', 'your.email@example.com')]

使用SendGrid发送电子邮件每月最多免费获得1.2万封电子邮件。

I found using SendGrid to be the easiest way to set up sending email with Django. Here’s how it works:

  1. Create a SendGrid account (and verify your email)
  2. Add the following to your settings.py: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = '<your sendgrid username>' EMAIL_HOST_PASSWORD = '<your sendgrid password>' EMAIL_PORT = 587 EMAIL_USE_TLS = True

And you’re all set!

To send email:

from django.core.mail import send_mail
send_mail('<Your subject>', '<Your message>', 'from@example.com', ['to@example.com'])

If you want Django to email you whenever there’s a 500 internal server error, add the following to your settings.py:

DEFAULT_FROM_EMAIL = 'your.email@example.com'
ADMINS = [('<Your name>', 'your.email@example.com')]

Sending email with SendGrid is free up to 12k emails per month.


回答 7

我实际上是在Django之前完成的。打开一个合法的GMail帐户,然后在此处输入凭据。这是我的代码-

from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

def sendmail(to, subject, text, attach=[], mtype='html'):
    ok = True
    gmail_user = settings.EMAIL_HOST_USER
    gmail_pwd  = settings.EMAIL_HOST_PASSWORD

    msg = MIMEMultipart('alternative')

    msg['From']    = gmail_user
    msg['To']      = to
    msg['Cc']      = 'you@gmail.com'
    msg['Subject'] = subject

    msg.attach(MIMEText(text, mtype))

    for a in attach:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(attach, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(a))
        msg.attach(part)

    try:
        mailServer = smtplib.SMTP("smtp.gmail.com", 687)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmail_user, gmail_pwd)
        mailServer.sendmail(gmail_user, [to,msg['Cc']], msg.as_string())
        mailServer.close()
    except:
        ok = False
    return ok

I had actually done this from Django a while back. Open up a legitimate GMail account & enter the credentials here. Here’s my code –

from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

def sendmail(to, subject, text, attach=[], mtype='html'):
    ok = True
    gmail_user = settings.EMAIL_HOST_USER
    gmail_pwd  = settings.EMAIL_HOST_PASSWORD

    msg = MIMEMultipart('alternative')

    msg['From']    = gmail_user
    msg['To']      = to
    msg['Cc']      = 'you@gmail.com'
    msg['Subject'] = subject

    msg.attach(MIMEText(text, mtype))

    for a in attach:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(attach, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(a))
        msg.attach(part)

    try:
        mailServer = smtplib.SMTP("smtp.gmail.com", 687)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmail_user, gmail_pwd)
        mailServer.sendmail(gmail_user, [to,msg['Cc']], msg.as_string())
        mailServer.close()
    except:
        ok = False
    return ok

回答 8

晚了,但是:

除了DEFAULT_FROM_EMAIL其他人提到的修复程序,允许安全性较低的应用访问该帐户外,我还必须以相关帐户的身份登录到https://accounts.google.com/DisplayUnlockCaptcha,以使Django最终通过身份验证。

我通过SSH隧道到达Web服务器的URL,以确保IP地址相同。我不确定这是否必要,但不会造成伤害。您可以这样操作:ssh -D 8080 -fN <username>@<host>,然后将Web浏览器设置localhost:8080为用作SOCKS代理。

Late, but:

In addition to the DEFAULT_FROM_EMAIL fix others have mentioned, and allowing less-secure apps to access the account, I had to navigate to https://accounts.google.com/DisplayUnlockCaptcha while signed in as the account in question to get Django to finally authenticate.

I went to that URL through a SSH tunnel to the web server to make sure the IP address was the same; I’m not totally sure if that’s necessary but it can’t hurt. You can do that like so: ssh -D 8080 -fN <username>@<host>, then set your web browser to use localhost:8080 as a SOCKS proxy.


回答 9

您可以使用“测试邮件服务器工具”来测试在您的计算机或本地主机上发送的电子邮件。Google并下载“测试邮件服务器工具”并进行设置。

然后在您的settings.py中:

EMAIL_BACKEND= 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25

从外壳:

from django.core.mail import send_mail
send_mail('subject','message','sender email',['receipient email'],    fail_silently=False)

You could use “Test Mail Server Tool” to test email sending on your machine or localhost. Google and Download “Test Mail Server Tool” and set it up.

Then in your settings.py:

EMAIL_BACKEND= 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25

From shell:

from django.core.mail import send_mail
send_mail('subject','message','sender email',['receipient email'],    fail_silently=False)

回答 10

对于 SendGrid-Django具体而言:

SendGrid Django文档在这里

在以下位置设置这些变量

settings.py

EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'sendgrid_username'
EMAIL_HOST_PASSWORD = 'sendgrid_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

在views.py中

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

For SendGrid – Django Specifically:

SendGrid Django Docs here

Set these variables in

settings.py

EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'sendgrid_username'
EMAIL_HOST_PASSWORD = 'sendgrid_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

in views.py

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。