Search code examples
pythonpython-3.xexceptionsmtplib

Unable to send email when exception is raised via smtplib python


I am wish to create a script that when encounters error sends me an email regarding the details of error. But when I call the method in except block it doesnot I do not recieve any email. But if I write normally that is outside except block I recieve the mail. Can you please tell me where I am doing wrong?

import smtplib
from datetime import datetime
import traceback
def senderrormail(script, err, date, time, tb = 'none'):
    sender = "Aayush Lakkad <alakkad@smtp.mailtrap.io>"
    receiver = "Aayush Lakkad <alakkad@smtp.mailtrap.io>"

    message = f"""\
    Subject: Hi Mailtrap
    To: {receiver}
    From: {sender}

    This is an alert mail,\n your python script for {script}\n has run into an error {err} \n\n on date {date} \t time {time} with {tb}"""
    try:
        with smtplib.SMTP('smtp.mailtrap.io', 2525) as server:
            server.login("xxxxxxx", "xxxxxxx")
            server.sendmail(sender, receiver, message)
            print('mail sent!')
    except:
        print('Mail not sent!')


now = datetime.now()
date = now.strftime("%d/%m/%Y")
time = now.strftime("%H:%M:%S")
try:
    raise TypeError('ohh')
except Exception as e:
    t = traceback.print_exc()
    senderrormail('emailalert', e, date, time)
    print(t)

Solution

  • You need to set an Google account for Developer. If you don't want change the security settings of the sending mail.There are two ways to start a secure connection with your email server:

    1.Start an SMTP connection that is secured from the beginning using SMTP_SSL(). 2.Start an unsecured SMTP connection that can then be encrypted using .starttls()

    And I saw you have used

    with smtplib.SMTP('smtp.mailtrap.io', 2525) as server
    
    

    Just add the script you want to find the error in your directory and I reccomend you to do:

    import smtplib, ssl
    import sys
    import filename #your script
    
    def senderrormail(script, err, date, time, tb = 'none'):
        port = 465  
        smtp_server = "smtp.gmail.com"
        sender_email = "your_sending_email"
        receiver_email = "receiver_email"  
        password = "your password"
    
        message = f"""\
        Subject: Hi Mailtrap
        To: {receiver}
        From: {sender}
    
        This is an alert mail,\n your python script for {script}\n has run into an error {err} \n\n on date {date} \t time {time} with {tb}"""}
    
        context = ssl.create_default_context()
    
    try:
        with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
            server.login(sender_email, password)
            server.sendmail(sender_email, receiver_email, message)
    except:
        print("Mail not sent!")
    
    
    now = datetime.now()
    date = now.strftime("%d/%m/%Y")
    time = now.strftime("%H:%M:%S")
    
    
    
    try:
        t = traceback.print_exc(limit=None, file=filename, chain = True)
        senderrormail(fiename, t, date, time)
        print(t)    
    
    except Exception as e:
        print("mail not sent")
    
    

    Hope this helps!