How to send a message to a gmail account from DJango

0

You see, I have created a view with which a person can send a message to an email address. I already have it ready, but there are a couple of failures: The first, although some factors, such as to which email address the message should be sent, are predetermined, the form also asks me to indicate them. Also, when I try to send the message, I get an error message: Unable to establish a connection since the destination team expressly denied such connection

Settings:

EMAIL_USE_TLS = True
EMAIL_HOST = 'localhost'
EMAIL_PORT = 587
DEFAULT_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''

Form code:

class correo(forms.Form):
    origen=forms.CharField()
    asunto=forms.CharField(required=True)
    destino=forms.EmailField()
    contenido=forms.CharField(max_length=999, widget=forms.Textarea)

View code:

class contacto(View):
    def get(self,request):
        form=correo()
        return render(request,'email.html',{'forma':form})
    def post(self,request):
        form=correo(request.POST)
        if form.is_valid():
            datos=form.cleaned_data
            send_mail(
                "<html><body>{{user.first_name}} {{user.last_name}}</body></html>", # El usuario escribe el mensaje.
                datos['asunto'],
                '[email protected]', # El destino.
                [datos['contenido']],
                fail_silently=False,
                )
            return HttpResponseRedirect('/')
        return render(request,'email.html',{'forma':form})

HTML code:

{% load bootstrap %}
{% load staticfiles %}
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Enviando un mensaje al administrador</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="{% static 'maquillar.css' %}">
<script src="{% static 'metodos.js' %}"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <h1 class="text-center text-muted">Formulario de Contacto</h1>
        <form method="POST" action="" novalidate="novalidate">
            {% csrf_token %}
            {{ forma|bootstrap }}
            <input type="submit" value="Confirmar" class="btn btn-success pull-right">
        </form>
    </div>
</div>
</body>
</html>

Edit: This is the new HTML code.

class contacto(View):
    def get(self,request):
        form=correo()
        return render(request,'email.html',{'forma':form})
    def post(self,request):
        form=correo(request.POST)
        if form.is_valid():
            datos=form.cleaned_data
            email=EmailMessage('title','body', to=['[email protected]'])
            email.send()
            return HttpResponseRedirect('/')
        return render(request,'email.html',{'forma':form})

The problem is that it gives me that the origin email is also called "[email protected]", even if the user has another email. How do I indicate the name of the email that sent the message?

    
asked by Miguel Alparez 15.05.2017 в 15:31
source

1 answer

2

To send emails from django you must:

Set the settings in settings:

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '**************'
EMAIL_PORT = 587

To allow google to send mails from this address you will have to access your account > Access and Security > Option Allow access for less secure applications: ACTIVATED

Afterwards, you will only have to go to your views and:

from django.core.mail import EmailMessage

email = EmailMessage('title', 'body', to=[email])
email.send()

in your view:

from django.core.mail import EmailMessage
class contacto(View):
    def get(self,request):
        form=correo()
        return render(request,'email.html',{'forma':form})
    def post(self,request):
        form=correo(request.POST)
        if form.is_valid():
            datos=form.cleaned_data

            email = EmailMessage('title', 'body', to=[email])
            email.send()

            return HttpResponseRedirect('/')
        return render(request,'email.html',{'forma':form})
    
answered by 16.05.2017 / 18:13
source