I have a project where we process data from various sources. My problem is I want a to send email every time there is an error or error raise my me.
Currently I do something like this where on every raise I send a email. But I want a system where on every error there would be a email sent.
# send an email alert
email_content = "Email content"
subject = "Subject"
if settings.ENVIRONMENT == 'PROD':
BaseScraper.email_alert_for_error(
subject,
email_content,
["admin#mail.com"],
)
else:
BaseScraper.email_alert_for_error(
subject,
email_content,
["admin#mail.com"],
)
You can use try: and except: like such:
try:
<do something>
except Exception as e:
email_content = email_content + e
BaseScraper.email_alert_for_error(
subject,
email_content,
["admin#mail.com"],
)
Here a list of keyword for exception: https://docs.djangoproject.com/en/4.1/ref/exceptions/
Related
I want to send account confirmation emails to all the users who sign up on my website, so it has to be an HTML email with the activation link. This is how i am trying to do it:
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
def my_view(request):
current_site = get_current_site(request)
mail_subject = 'Welcome To IIITU Alumni Network'
to_email = email
ctx = {
'user': user,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
'token':account_activation_token.make_token(user),
}
message = Mail(
to_emails = to_email,
from_email = '<my email address>',
subject = mail_subject,
#I made this html page specifically for sending confirmation email
#I am not sure if this is the correct way to do it
html_content = render_to_string('network/email.html', ctx)
)
try:
#I have this key as an environment variable
sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
#Now this is where the problem is
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
return HttpResponse("A confirmation Email has been sent to your Institute email address. Please Confirm Your email to complete your registration")
except Exception as e:
print(e.message)
return HttpResponse("The Server seems too busy!! Sorry for the inconvenience. Please try again later, or contact administrator if this problem persists.")
When this particular view is rendered, it throws the following error message:
'UnauthorizedError' object has no attribute 'message'
Since this doesn't send the emails via an SMTP server, according to my understanding i don't need to add anything to my settings.py file(i did add 'sendgrid' to my installed apps after i installed it using pip)Can someone please point out what i did wrong? I have been stuck on this for a while now...
Thank you for your time
I think this line is causing an error.
...
except Exception as e:
print(e.message)
...
Whatever exception is occuring, it doens't have message property.
Two solutions.
print(e)
remove try except block and try to figure out which exception is occurring and then catch that specifically.
I have the following code that I believed would help me check if email is provided is valid and would be accepted for delivery:
#app.route("/email_send/<email>")
def email_send(email=None):
return_message=None
msg = Message('Online Enquiry', sender='sender#gmail.com', recipients=[email])
msg.body ='We have received your message. We shall be communicating with you'
try:
mail.send(msg)
return_message='SUCCESS'
except Exception as e:
return_message='FAILED'
return json.dumps(str(return_message))
The problem is that it is always returning 'SUCCESS' even when I get address not found in gmail
I'm having a strange problem.
This code appears to be fine, but it returns "The template data is invalid" every single time.
Am I doing something wrong?
Can it be a Bug?
Thanks
--
MacOS, latest version.
Python 3.6.6
boto3==1.9.57
import boto3
verified_email='theemail#examplemail.com'
template_name = "TestTemplateDeleteMe"
template = {
"TemplateName": template_name,
"SubjectPart": "Test send bulk template email",
"HtmlPart": "<h1>Hello {{name}},</h1>Favorite animal is {{favorite_animal}}.",
"TextPart": "Dear {{name}},\r\nYour favorite animal is {{favorite_animal}}."
}
client = boto3.client('ses', region_name='eu-west-1')
try:
client.create_template(Template=template)
except Exception as e:
print(str(e))
try:
if e.response['Error']['Code'] != 'AlreadyExists':
raise e
except KeyError:
raise e
response = client.send_bulk_templated_email(
Source=verified_email,
Template='TestTemplateDeleteMe',
Destinations=[{'Destination': {'ToAddresses': [verified_email]}}],
DefaultTemplateData='{"name": "TestEmailPerson", "favorite_animal": "TestEmailAnimal"}'
)
print(response)
def GetMessage(service, user_id, msg_id):
"""Get a Message with given ID.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
msg_id: The ID of the Message required.
Returns:
A Message.
"""
try:
message = service.users().messages().get(userId=user_id, id=msg_id).execute()
return message
except errors.HttpError, error:
print 'An error occurred: %s' % error
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
results = service.users().messages().list(userId='me', labelIds='UNREAD').execute()
messages = results.get('messages', [])
for msg in messages:
id = msg['id']
msgobj = GetMessage(service, 'me', id)
print msgobj['snippet']
when you are replying back via gmail, you have your message and then the message from previous replies. The 'snippet' part of message picks up reply as well. I would like to just get the latest text in the email(not the reply part)
yeah that sounds good
On Sun, Feb 21, 2016 at 7:36 PM, <apple#gmail.com> wrote:
you want to play ball? ________________________________________ From: banana#gmail.com
is there anything else besides snippet that gets latest email text?
Nothing much can be done with it, unfortunately. snippet is a short part of the message, which (based on API Explorer observations) usually is around 100+- characters. If the message was too short, it will get the reply part of the preceding message.
What I observed though, is that the message part of the snippet usually has the On [date] statement. I think an approach would be for you to check and split the message if a phrase like that was made (this will be a bit tricky though since the phrase itself can be partial as well).
def GetMimeMessage(service, user_id, msg_id):
"""Get a Message and use it to create a MIME Message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
msg_id: The ID of the Message required.
Returns:
A MIME Message, consisting of data from Message.
"""
try:
message = service.users().messages().get(userId=user_id, id=msg_id,
format='raw').execute()
#print 'Message snippet: %s' % message['snippet']
msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
mime_msg = email.message_from_string(msg_str)
for part in mime_msg.walk():
if part.get_content_type() == 'text/plain':
print part.get_payload()
return mime_msg
except errors.HttpError, error:
print 'An error occurred: %s' % error
I've decided to get Mimemessage instead. This seems to always have the reply part if there is one. This makes it easier to look for it and parse them out
Following the directions in Python's email examples and in several Stack Overflow questions, I wrote the following function (sending through the Gmail SMTP server):
def send_email(emailaddr, message, attachmentfile = None, subject = None):
try:
smtpconn = smtplib.SMTP(mainconf["SMTPHOST"], mainconf["SMTPPORT"])
smtpconn.set_debuglevel(1)
smtpconn.ehlo()
smtpconn.starttls()
smtpconn.login(mainconf["SMTPUSER"], mainconf["SMTPPASS"])
if not attachmentfile:
message = '\n' + message
smtpconn.sendmail(mainconf["EMAILFROM"], emailaddr, message)
else:
multipart = MIMEMultipart()
multipart['Subject'] = subject if subject else "Attachment"
multipart['From'] = mainconf["EMAILFROM"]
multipart['To'] = emailaddr
with open(attachmentfile, 'rb') as fp:
filepart = MIMEApplication(fp.read())
multipart.attach(filepart)
multipart.attach(message)
smtpconn.sendmail(mainconf["EMAILFROM"], emailaddr, multipart.as_string())
generallog.info("Sent an email to {0}".format(emailaddr))
except:
generallog.warn("Email sending to {0} failed with error message {1}".format(emailaddr, traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1])))
This works fine for sending an email with an attachment, but it results in the famous noname problem (that's just one of several SO questions on the subject). So I add in this:
filepart.add_header('Content-Disposition','attachment',filename=os.basename(attachmentfile))
Then Gmail simply refuses to send the email. When I run this code in the Python shell, I get the standard message accepted message, but the message is never delivered.
Why might this be happening?