Programing

Django를 통해 이메일을 보내는 방법은 무엇입니까?

lottogame 2020. 6. 16. 21:01
반응형

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 (simple ubuntu pc)를 사용하여 이메일을 보낼 수 없습니까?

  2. 장고 1.3 send_mail()에서는 다소 사용되지 않으며 EmailMessage.send()대신 사용 된다고 생각했습니다 .


이메일을 실제 SMTP 서버로 보냅니다. 직접 설정하지 않으려는 경우 Google과 같이 회사를 운영하는 회사를 찾을 수 있습니다.


Django의 SMTP 서버로 Gmail을 사용합니다. 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 옵션을 허용 할 수 있습니다.


  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_mailEmailMessage기능을 참조하십시오 .

Gmail 업데이트

또한 Gmail을 통해 이메일을 보내는 데 문제가있는 경우 Google 에서이 가이드 를 확인하십시오 .

Google 계정 설정 Security > Account permissions > Access for less secure apps에서이 옵션으로 이동하여 활성화하십시오.

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.


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


My site is hosted on Godaddy and I have 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 recieved the mail too. :)


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.


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.


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

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.


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)

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)

참고URL : https://stackoverflow.com/questions/6367014/how-to-send-email-via-django

반응형