EmailMessage 'sender' issue - django

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).

Related

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).

How to send event email request from gmail to outlook in Django 2

I was trying to create an appointment management system where user can send invitation meeting mail to admin. I can send single mail from user to admin but how could I send an event email from Gmail to outlook
Here is my settings.py code
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'appoint#gmail.com'
EMAIL_HOST_PASSWORD = '******'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
here is my views.py
def sendRequest(request):
email = EmailMessage('Subject', 'Body', to=['appoint#dekkotops.com'])
email.send()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Now I need to send event email not a single mail from my system Gmail account
I do some google about this but not find any proper solution step by step
What you can do is to create a .ics file with the invitation information (you may use a Django template to write a .ics file or just generate it using plain Python code).
You can see the .ics file specification and read more about it here:
https://en.wikipedia.org/wiki/ICalendar
Then you could just attach this .ics file to your email message:
email = EmailMessage('Meeting invitation', 'Email body...', 'noreply#example.com', ['recipient1#example.com', ])
email.attach('invite.ics', invite_file_content, 'text/calendar')
email.send()
Alternatively you can use this third-party app django-cal
Maybe this post can also give you some insights on the issue:
How can I get a meeting invitation to integrate properly with Gmail/Google Apps?
First Need To Create a .ics file
BEGIN:VCALENDAR
METHOD:REQUEST
PRODID:Microsoft Exchange Server 2010
VERSION:2.0
BEGIN:VTIMEZONE
TZID:Bangladesh Standard Time
BEGIN:STANDARD
DTSTART:16010101T000000
TZOFFSETFROM:+0600
TZOFFSETTO:+0600
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:16010101T000000
TZOFFSETFROM:+0600
TZOFFSETTO:+0600
END:DAYLIGHT
END:VTIMEZONE
BEGIN:VEVENT
ORGANIZER;CN=dekkoappoint:MAILTO:dekkoappoint#dekkotops.com
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-
ACTION;RSVP=TRUE;CN=sendusermail#gmail.com:MAILTO:sendusermail#gmail.com
DESCRIPTION;LANGUAGE=en-US:Hi This is a test mail\n
UID:040000008200E00074C5B7101A82E008000000009CCD2D80E57BD401000000000000000
010000000F02E168DB7BF3A4BAC1FAE1547D716BE
SUMMARY;LANGUAGE=en-US:Test Event
DTSTART;TZID=Bangladesh Standard Time:20181115T130000
DTEND;TZID=Bangladesh Standard Time:20181115T140000
CLASS:PUBLIC
PRIORITY:5
DTSTAMP:20181114T064433Z
TRANSP:OPAQUE
STATUS:CONFIRMED
SEQUENCE:0
LOCATION;LANGUAGE=en-US:Dhaka University Area (Dhaka University Area Dhaka\
, Bangladesh)
X-MICROSOFT-CDO-APPT-SEQUENCE:0
X-MICROSOFT-CDO-OWNERAPPTID:2116776604
X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE
X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY
X-MICROSOFT-CDO-ALLDAYEVENT:FALSE
X-MICROSOFT-CDO-IMPORTANCE:1
X-MICROSOFT-CDO-INSTTYPE:0
X-MICROSOFT-DONOTFORWARDMEETING:FALSE
X-MICROSOFT-DISALLOW-COUNTER:FALSE
X-MICROSOFT-LOCATIONDISPLAYNAME:Dhaka University Area
X-MICROSOFT-LOCATIONSOURCE:Device
X-MICROSOFT-LATITUDE:23.7303
X-MICROSOFT-LONGITUDE:90.3933
X-MICROSOFT-LOCATIONCITY:Dhaka University Area
X-MICROSOFT-LOCATIONSTATE:Dhaka
X-MICROSOFT-LOCATIONCOUNTRY:Bangladesh
X-MICROSOFT-LOCATIONS:[{"DisplayName":"Dhaka University Area"\,"LocationAnn
otation":""\,"LocationSource":3\,"LocationUri":""\,"Latitude":23.7303\,"Lo
ngitude":90.3933\,"LocationStreet":""\,"LocationCity":"Dhaka University Ar
ea"\,"LocationState":"Dhaka"\,"LocationCountry":"Bangladesh"\,"LocationPos
talCode":""\,"LocationFullAddress":""}]
BEGIN:VALARM
DESCRIPTION:REMINDER
TRIGGER;RELATED=START:-PT15M
ACTION:DISPLAY
END:VALARM
END:VEVENT
END:VCALENDAR
After that in view.py
from django.core.mail import EmailMessage
def sendRequest(request):
email = EmailMessage('Subject', 'email body', 'sendfrom#gmail.com', ['getfrom#gmail.com'])
email.attach_file('assets/invite.ics', 'text/calendar')
email.send()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

How to detect error when not connected to mail server from Django?

I have the following in my settings.py:
EMAIL_HOST = 'mail.domain.com'
EMAIL_HOST_USER = 'user#domain.com'
EMAIL_HOST_PASSWORD = '******'
EMAIL_PORT = 567
EMAIL_USE_TLS = True
I have the following code to send email:
email = EmailMessage()
email.subject = subject
email.body = body
email.from_email = from_email
email.to = to
email.attach(file_name, pdf, 'application/pdf')
email.send()
Sometimes our server is down and there is no way for me to detect if the mail was sent or not. One way I can think of is to show Mail not sent error when Django cannot connect to mail server. How can I detect a failed connection to the server?
You can use try except.
try:
email.send()
except Exception as e:
print str(e.message)
# you can do some action.

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()

sending email with gmail smtp

I have this in my setting.py file:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'from#gmail.com'
EMAIL_HOST_PASSWORD = 'Pass'
I want to send email to destinations posted from a template:
from django.core.mail.message import EmailMessage
destinations = request.POST['destinations'] #this return string with 2 emails ('fst#gmail.com; sd#gmail.com')
EmailMessage(subject, core, to=[destinations]).send()
it send email just to the first mail and not for others !
is there any action to make this work for all emails posted ?
Pass a list to to:
import re
# or you can use request.getlist('destination')
# I do not know how you generate the two mail addresses
destinations = re.split(r'[;\s]*', request.POST['destinations'])
EmailMessage(subject, content, to=destinations)