Catching smtp exception in EmailMultiAlternatives django - python

I am writing a management command where I will be sending emails to multiple recipients. I would like to make a log where I can tell if the mail is sent to a recipient successfully or not. So far I am able to get this much code running
from django.core.mail import EmailMultiAlternatives
from smtplib import SMTPException
try:
msg = EmailMultiAlternatives(data['subject'], data['text_content'], data['from_mail'], data['recipient_list'], bcc=data['bcc_address'])
if data['html_content']:
msg.attach_alternative(data['html_content'], "text/html")
msg.send(fail_silently=False)
except SMTPException as e:
error_code,error_msg = e.smtp_code, e.smtp_error
print error_code, error_msg
'''except Exception as e:
print e
print "==========="
print traceback.print_exc()'''
I am kind of stuck now. I deliberately put the wrong recipient emails in data['recipient_list'], but still I am not able to catch the error. I am not sure what I am doing wrong. What is to correct way to catch smtp exception in django

It won't work this way. SMTP server will send email regardless of whether such email exists or not. You may receive bounce email to your inbox later, but this is different case.
I'd say that should validate email address syntax and that's all you can do. You can also take benefit of send() return value which is number of emails sent.

Related

Sending email via Outlook using Python, contact group doesn't resolve

The recipient address and the distro lists do not immediately resolve. Outlook is smart enough to recognize the email addresses, but it doesn't recognize my distro list. At least not immediately.
I'm using Office 365 if that matters.
from win32com.client import Dispatch
outlook = Dispatch('Outlook.Application')
Mail_Item = outlook.CreateItem(0)
# This sends no problem
# Mail_Item.To = 'first.last#company.com'
# This does not send
Mail_Item.To = 'Contact_Group_Test'
Mail_Item.Subject = "Subject_text"
Mail_Item.Body = "Body_text"
Mail_Item.Recipients.ResolveAll()
Mail_Item.Send()
While troubleshooting I used Mail_Item.Display() to see the message. After a few seconds it resolves all my addresses, including the contact group. HOWEVER, the contact group itself still doesn't work despite this.
If you couldn't solve, you can try smtplib.
import smtplib
sender = 'from#fromdomain.com'
receivers = ['to#todomain.com']
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
If you will send mail from outlook account, you have to write smtp-mail.outlook.com instead of localhost
mtbenj's answer may work for others. I'm just choosing to go the win32com route because of my organization.
For whatever reason using 'Test', and I'm assuming, any one-word contact list takes ~5 seconds to resolve. I counted after the .Display() popup came up. Naming it 'Test_' didn't do it for me either.
I decided to try one named 'Test_Test'. After calling .Recipients.ResolveAll(), it works perfect.
So use an underscore and multiple words.

Python SMTP Verify email

import smtplib
try:
server = smtplib.SMTP("smtp.gmail.com:587")
server.ehlo()
server.starttls()
server.login("MY USER", "MY PASS")
message = "Hi, recruit?"
server.sendmail("FROME WHO", "TO WHOM", message)
server.quit()
print("email is valid")
except:
print("email invalid")
Goal: I need to verify if the email I'm sending does exist. I would like the script to give me a traceback if the email doesn't exist.
Problem: The email get's sent even when the email doesn't exist, I get to receive email from google though saying that the email doesn't exist in my Gmail.
steps taken: I've tried the instance method SMTP.verify which would send me a status code of 404 if the email doesn't exist, but the email is getting sent even though it doesn't exist.
Question: is there a setting in Gmail where I can change to say if an email doesn't exist, please give me an error. Or maybe there's a workaround on my script that I didn't know yet?
This is the code for verify and also the return
https://i.stack.imgur.com/MTZJE.png

Python sending e-mail with SMTP without authentication

I'm making a script that notifies people about some pending tickets in JIRA. These notifications are sent by e-mail, I already got the notification to trigger, but I'm having problems sending the emails.
I can send them using gmail but when I tried to do it with my official account (the one that the company gave me) I am not able to send them. IT guys already provided me the 'localhost' because they use SMTP relays and the port, but they keep telling me that I should start SMTP without authentication, I'm not very sure of how to do this.
The example I found on internet was this:
import smtplib
fromaddr = 'Axel.Sa#mydomain.com'
toaddrs = ['Axel.Sa#mydomain.com']
msg = '''
From: {fromaddr}
To: {toaddr}
Subject: testin'
This is a test
.
'''
msg = msg.format(fromaddr=fromaddr, toaddr=toaddrs[0])
server = smtplib.SMTP('localhost:25')
server.starttls()
server.ehlo("mydomain.com")
server.mail(fromaddr)
server.rcpt(toaddrs[0])
server.data(msg)
server.quit()
But I keep getting this error, If someone can tell me the proper way of sending emails by SMTP without authentication I will be very grateful.
Check this stack:
How to send an email without login to server in Python
change your smtplib.SMTP('localhost:25') to smtplib.SMTP('localhost', 25)

Send email to a mailing list using Python

I'm trying really hard to check why this is happening but not really sure if its on gmail's server side or in a part of the script I'm using.
The problem is that I'm trying to send an email to a mailing list (I have found many posts explaining how to include various emails but none explaining if there is a limitation or workaround to send it to a single email which contains multiple addresses).
In this case I want to send the email to many different people which make part of the BI team of our company (bi#company.com), normally sending an email to this address will result in everyone from the team getting the email, but I can't manage to make i work, and I don't want to include all emails in the list because there are too much and it will have to be manually changed every time.
When I try this with another single person email it works perfectly
import smtplib
sender = 'server#company.com'
receivers = ['bi#company.com']
q = ""
message = """From: Error alert <Server-company>
To: BI <bi#company.com>
Subject: Error e-mail
%s
""" % q
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Alright. I found out why this was not working in my organization. Hopefully this can help someone else out. The outlook groups were setup to only work from an internal email address.
Sending emails programmatically, may use a relay method, which has no authentication. As such the email will never go through. The fix is to have the Network ops people (or exchange group) at your company turn on receiving external emails. The emails will then go through.
make recivers a list of emails you want to send:
example:
recivers = ['a#gmail.com','b#gmail.com,...]
try like this:
import smtplib
from email.mime.text import MIMEText
sender = 'server#company.com'
receivers = ['a#company.com','b]#company.com'....]
server = smtplib.SMTP('smtp#serv.com',port)
server.starttls()
msg = MIMEText('your_message')
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(receivers)
server.login('username','password')
server.sendmail(sender, recipients, msg.as_string())
server.quit()
I finally decided to stick to writing the full list of email addresses inside the list. Apparently if mailing lists are managed locally the re distribution of the emails cant be done.

What is the proper way to verify an EmailMessage for proper recipient email addresses?

I am developing an application with Django. In forms.py, where the classes for my forms are stored, I have written a clean function to verify that all the emails typed into a textbox adhere to the proper format (person#site.com).
In this clean function, I build the email message with an EmailMessage object:
def clean_recipients(self):
rec = self.data['recipients'].split(",")
recList = []
for recipient in rec:
reci = str.strip(str(recipient))
recList.append(reci)
message = (self.data['subject'], self.data['message'], 'hi#world.com', recList)
mail = EmailMessage(self.data['subject'], self.data['message'], 'from#somebody.com', ['email_list#mysite.org'], recList)
try:
mail.send(fail_silently=False)
except Exception:
raise forms.ValidationError('Please check inputted emails for validity.')
return self.data['recipients']
However, the exception 'Please check inputted emails for validity.' is never raised on the form regardless of what I input into the textbox. If I input random characters into the textbox, simply no message is sent.
What is the proper way to catch if the email was not sent properly?
Thank you.
Try to clean recipients emails format only in the clean_recipients. There is snippet how to check email. http://djangosnippets.org/snippets/1093/ . Raise validation error if email format does not match.
Create email and send it from the form's clean method (if you need show sending errors. You will need check for form errors before send.) or from the view.
PS. get your data this way - self.cleaned_data instead of self.data.

Categories

Resources