I'm trying to implement an automatic email sending system with gmail on my django app.
This is my view:
from .forms import EmailPostForm
from django.core.mail import send_mail
def post_share(request, post_id):
#retrive post by #
post = get_object_or_404(Post, id=post_id, status='published')
sent=False
if request.method == 'POST':
# Form was submitted
form = EmailPostForm(request.POST)
if form.is_valid():
# Form passes validation
cd = form.cleaned_data
#...send Email
post_url = request.build_absolute_uri(post.get_absolute_url())
subject = f"{cd['name']} recomends you read {post.title}"
message = f" Read {post.title} at {post_url}\n\n" \
f" {cd['name']}\s comments: {cd['comments']}"
send_mail = (subject, message, 'my_gmail_acccount@gmail.com', [cd['to']])
sent=True
else:
form = EmailPostForm()
context = {
'form':form,
'post':post,
'sent': sent
}
return render(request, 'byExample_django3/post/share.html', context)
and my form:
from django import forms
class EmailPostForm(forms.Form):
name = forms.CharField(max_length=25)
email = forms.EmailField()
to = forms.EmailField()
comments= forms.CharField(required=False, widget=forms.Textarea)
and my template:
{% extends "byExample_django3/base.html" %}
{% block title %}Share a post{% endblock %}
{% block content %}
{% if sent %}
<h1>E-mail successfully sent</h1>
<p>
"{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}.
</p>
{% else %}
<h1>Share "{{ post.title }}" by e-mail</h1>
<form method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="Send e-mail">
</form>
{% endif %}
{% endblock %}
and my url:
path('<int:post_id>/share', views.post_share, name='post_share')
I think I have configured my settings correctly:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'my_gmail_account@gmail.com'
EMAIL_HOST_PASSWORD='my_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
I tried first on the django shell with send_mail:
send_mail = ('django test mail', 'django test mail content', 'my_gmail_account@gmail.com', ['my_gmail_account@gmail.com'], fail_silently=False])
and everything worked correctly, but when I try it on the browser, I receive the message that email was sent but nothing happens.
Any help?
thank you very much
Carlo