Email sending from address is gmail with django - django

Minor but annoying issue, I have setup my django app to use my company's gmail account to send emails. The sending works fine, but the from in the emails is always the gmail account. Here are me settings/code - I have changed all the addresses etc, but to be sure everything works fine except for the from e-mail.
def send_discrepency_email(action, cart, atype):
r = False
user = cart.user
subject = "%s - User Discrepency Response for order %s (%s)" % (action.upper(), cart.web_order_id, cart.syspro_order_id)
message = "The user %s (%s) has opted to %s his/her order with the following discrepency type: %s." %(user.email, user.customer_id, action.upper(), atype)
try:
e = EmailMessage(subject, message, 'no-reply#rokky.com', ["ecommerce_requests#rokky.com", "pewet#s6688m.com"])
e.send(fail_silently=False)
r = True
except Exception as e:
print "Error sending discrepency email: %s" % e
return r
Note: for the code I have also tried overriding with the headers kwarg to no avail.
DEFAULT_FROM_EMAIL = "ecommerce_requests#rokkyy.com"
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'no-actual-account#gmail.com'
EMAIL_HOST_PASSWORD = 'fakepword'
EMAIL_PORT = 587
Is this even doable with gmail, I swear I used this once before and it worked fine.
In short, no matter what changes I make, the FROM email is always no-actual-account#gmail.com

This is a security setting with gmail. I ran into this issue with a rails app that I wrote. The from address must either be the account you sign in with aka 'no-actual-account#gmail.com' or an alias to that account. You can always just set the reply-to and get a similar effect to changing the from address. Or you will have to use a different SMTP server.

Related

Unable to send emails through Flask-mail

I have been trying to create a web app which takes email address as an input through HTML form and sends a one time pin for further access to website.
I have 2 html files in my template folder (one for taking user's email address and other for OTP entering)
i have config.json file which stores my accountid and password through which i intend to send the OTP.
.py file
from flask import Flask, render_template, request
from random import randint
import json
from flask_mail import *
with open('config.json','r') as f:
params = json.load(f)['params']
mail = Mail(app)
otp = randint(100,999) #otp production
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = params['gmail-user']
app.config['MAIL_PASSWORD'] = params['gmail-password']
#app.route('/')
def home():
return(render_template('otpgive.html'))
#app.route('/getOTP', methods = ['POST'])
def getOTP(): #OTP send and Verify here
email_id = request.form['usermail']
msg = Message('OTP for the APPLICATION', sender = 'my_email', recipients = [email_id])
#my_email is the email through which i plan to send messages.
msg.body = "Greetings! Your email has been verified successfully. Kindly note your OTP is " + str(otp)
mail.send(msg)
return render_template('otpconfirm.html')
#app.route('/validateOTP', methods = ['POST'])
def validateOTP():
userotp = request.form['otp']
if (otp == int(userotp)):
return ("Email Verified Succcessfully ")
else:
return render_template('otpgive.html',msg = 'incorrect otp')
if __name__ == '__main__':
app.run(debug = False)
#app.run(host='0.0.0.0',port=5000, debug = True)
Solutions I tried but failed:
Tried disabling the firewall.
Tried setting the port number for 0.0.0.0
Tried debug = False
I was expecting it to work. i.e send emails to the users but it shows ConnectionError or InternalServerError
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
ConnectionRefusedError:
[WinError 10061] No connection could be made because the target machine actively refused it
I finally got the solution.
Since I was using G-Mail, I had to enable 2FA (2-Factor Auth) first on my profile, and then generate a new password for my app.
The password thus obtained was pasted in the config.json file instead of my
main profile password.
Used directions from this thread Less Secure option in gmail unavailable
Now Changes I made in my code:
Reverted back to ip: host='0.0.0.0', port=5000, debug = True
I kept firewall disabled as a precaution.
I repositioned mail = Mail(app) line to after all app.configs

Send a mail from Django via Amazon SES

I am trying to send a mail from my django app via Amazon SES but I keep getting the following error:
smtplib.SMTPSenderRefused: (501, b'Invalid MAIL FROM address
provided', '=?utf-8?q?AKIAWMDVL5UEWNT3ODOO?=')
These are the settings that I am using:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'email-smtp.ap-south-1.amazonaws.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'smtp credential key'
EMAIL_HOST_PASSWORD = 'smtp credential password'
EMAIL_USE_TLS = True
and here's the code:
class CompanyCreateAPIView(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request):
email = request.data["company_email"]
phone = request.data["company_phone"]
def random_with_N_digits(n):
range_start = 10 ** (n - 1)
range_end = (10 ** n) - 1
return randint(range_start, range_end)
code = random_with_N_digits(4)
subject = 'Comapny Creation'
message = 'Company Code is {}'.format(code)
email_from = settings.EMAIL_HOST_USER
recipient_list = [str(email), ]
send_mail(subject, message, email_from, recipient_list)
I tried changing the port but it doesn't work, I have verified the email address in SES.. What is it that I am missing ?
You probably do not want to use the SMTP credentials username as the "email from" value. That should be something human readable, whatever you want your recipients to see as the address where the email came from. That address and/or domain also need to be whitelisted in the SES settings.
In Django's settings.py, set the DEFAULT_FROM_EMAIL setting to that address:
DEFAULT_FROM_EMAIL = 'info#example.com'
Do not pass email_from as an explicit setting to send_mail, unless you want to override it for specific emails (e.g. send from info#... for certain emails and newsletter#... for other kinds of emails).

raise SMTPSenderRefused(code, resp, from_addr)

registration app .
I follow toturial on http://agiliq.com/books/djenofdjango/chapter5.html for setting up an
email verfication and it suggest following confgiuration for setting.py
EMAIL_USE_TLS = True
EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_USER = "user#example.com"
EMAIL_HOST_PASSWORD = "secret"
EMAIL_PORT = 587
but i got error about SMTP supporting of TLS in some forum I read to comment the EMAIL_USE_TLS
then I got the aut method error and again from some forum I read to comment EMAIL_HOST_USER = "user#example.com" and EMAIL_HOST_PASSWORD = "secret" but know I got the following error :
raise SMTPSenderRefused(code, resp, from_addr)
Exception Type: SMTPSenderRefused at /accounts/register/
Exception Value: (502, '5.5.1 Unrecognized command. h47sm103656655eey.13 - gsmtp', u'webmaster#localhost')
I'm really confused about how to config setting.py for sending email .
I was having the same problem. but I stumbled on this https://accounts.google.com/DisplayUnlockCaptcha and I followed. It tourned out the 2-Step-Verification wasn't allowing my app to send any mail.
I just clicked on the link related to 2-Step-Verification and end up Signing in using App Passwords
by changing :
EMAIL_HOST_PASSWORD = "secret"
to the generated 16-characters password :
EMAIL_HOST_PASSWORD = "newlygeneratedsecret"
Hope I helped. I'm told ( https://webapps.stackexchange.com/questions/44768/limitations-on-sending-email-through-gmail-smtp/48393#48393 ) that if Gmail sees you sending a lot of e-mails, it may request you to manually sign in. But I'm not sure.
Please try using the below code. I have used the below code and got the solution for the above-mentioned issue. I am sending HTML body that's why I have used MIMEText(variable, "html") if you want to use text please use MIMEText(variable, "text").
me = "your email"
you = "email of person whom you want to send the mail"
msg = MIMEMultipart("alternative")
msg["Subject"] = "Subject String"
msg["From"] = me
msg["To"] = you
# message to be sent
#for HTML as a part of mail body
html = '<html><body><p></a>Testing HTML/a></p></body></html>'
part2 = MIMEText(html, "html")
msg.attach(part2)
s = smtplib.SMTP("smtp.gmail.com", 587)
s.starttls()
s.login(me, "password of your mail")
# sending the mail
s.sendmail(me, you, msg.as_string())
# terminating the session`enter code here`
s.quit()

Send_mail in Django, works in shell, works locally, not in view

I'm not even sure how to debug this: I'm using send_mail in one of my views in Django. It works fine when using the app locally (using the same SMTP settings I use in production), and it works fine from the shell in production (again, using the same settings). But when I actually use the app in production, the message doesn't send. Any idea how to troubleshoot?
I won't paste in the whole view, but here's the relevant section.
if request.method == 'POST':
message, form = decideform(request.POST)
if form.is_valid():
invitation.status = form.cleaned_data['status']
invitation.save()
message, form = decideform(request.POST)
update = 'Thank you for updating your status.'
# Send an email confirming their change
subject = 'Confirming your RSVP [%s %s]' % (invitation.user.first_name, invitation.user.last_name)
body = message + ' Remember, the URL to update or change your RSVP is http://the.url%s.' % invitation.get_absolute_url()
send_mail(subject, body, 'rsvp#mydomain.com', ['rsvp#mydomain.com', invitation.user.email], fail_silently=True)
And here's the relevant bits from my local_settings file, with salient details altered for security's sake:
EMAIL_HOST = 'mail.mydomain.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'rsvp#mydomain.com'
DEFAULT_FROM_USER = 'rsvp#mydomain.com'
EMAIL_HOST_PASSWORD = 'p4ssw0rd'
Check permissions. It could be that you have permissions to run send_mail, but the app doesn't.
I am having the same issue. 3 years after :)
copying the code of send_mail inline fixed it but I still don't know why
connection = django.core.mail.get_connection(username=None, password=None, fail_silently=False)
mail = django.core.mail.message.EmailMessage('hello', 'world', 'test#gmail.com', ['test#gmail.com'], connection=connection)
mail.send()
You can try django-sendgrid instead which is very easy to configure.Use settings like this
EMAIL_BACKEND = "sgbackend.SendGridBackend"
SENDGRID_USER = 'xxxxxx'
SENDGRID_PASSWORD = 'xxxxxx'
EMAIL_PORT = 1025

EmailMessage 'sender' issue

i am working on a contact form to receive emails from users. I am using EmailMessage(django 1.3). the problem is, i am able to receive the emails but the 'from'or 'sender' shows email_host_user email instead of the user's email.
so if user has email address user#gmail.com, when i receive the email
from: email#gmail.com
subject: some subject
to: moderator#email.com
instead of
from: user#gmail.com
subject: some subject
to: moderator#email.com
heres a part of the settings
EMAIL_HOST = 'smtp.googlemail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_HOST_USER = 'email#gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
REVIEW_MODERATOR ='moderator#email.com'
#heres part of the helpers.py
def run(self):
html = get_template(self.kwargs['template'])
html_content = html.render(Context(self.kwargs['context']))
msg = EmailMessage(
self.kwargs['subject'],
html_content,
self.kwargs['sender'],
[self.kwargs['email']],
bcc=[a[1] for a in settings.ADMINS])
msg.content_subtype = "html" # Main content is now text/html
try:
path = self.kwargs['file_path']
except KeyError:
pass
else:
msg.attach_file(path)
msg.send()
#heres part of the contact view
if contact_form.is_valid():
cdata = contact_form.cleaned_data
c={'name':cdata['name'], 'email':cdata['email'],'message':cdata['message']}
EmailThread(**{
'email':settings.REVIEW_MODERATOR,
'sender':cdata['email'],
'subject':email_subject,
'context':c,
'template':template
}).start()
Gmail doesn't let you send as arbitrary senders.
The way around this problem (I was dealing with the exact issue: customer service forms that send us email) is to use one of a very inexpensive SMTP services, or just settle with "reply-to" headers which are still quite functional (email is from from me#gmail.com but clicking reply will point to the reply-to address).