Smtp delivery receipt by using gmail smtp server

471 Views Asked by At

I want to get the delivery notification after sending a mail whether is was success or failure, on google I got to know about DeliveryNotificationOptions, but when i tried to create one poc to check this I am not getting proper answer.

 class Program
    {
        static string smtpAddress = "smtp.gmail.com";
        static int portNumber = 587;
        static bool enableSSL = true;
        static string emailFromAddress = "[email protected]"; //Sender Email Address  
        static string password = "password"; //Sender Password  
        static string emailToAddress = "[email protected]"; //Receiver Email Address  
        static string subject = "Hello";
        static string body = "Hello, This is Email sending test using gmail.";
        static void Main(string[] args)
        {
            SendEmail();
        }
        public static void SendEmail()
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(emailFromAddress);
                mail.To.Add(emailToAddress);
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = true;
                //mail.Attachments.Add(new Attachment("D:\\TestFile.txt"));//--Uncomment this to send any attachment  
                using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                {
                    smtp.Credentials = new NetworkCredential(emailFromAddress, password);
                    smtp.EnableSsl = enableSSL;

                    mail.Headers.Add("Disposition-Notification-To", emailToAddress);

                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                    smtp.Send(mail);
                  
                }
            }
        }
    }

On output I am getting success even though the from email is wrong. Can someone please help me to explain how can I achieve this scenario.

Thanks, Shreya

2

There are 2 best solutions below

0
On

I also found different workaround using ASPNETMX , you can find Licence-key, Code example and Dll on that site

class Program
    {
        static string smtpAddress = "smtp.gmail.com";
        static int portNumber = 587;
        static bool enableSSL = true;
        static string emailFromAddress = "MYID"; //Sender Email Address  
        static string password = "password"; //Sender Password  
        static string emailToAddress = "RecieverID"; //Receiver Email Address  
        static string subject = "Hello";
        static string body = "Hello, This is Email sending test using gmail.";
         static void Main(string[] args)
        {
            SendEmail();
        }
public static void SendEmail()
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(emailFromAddress);
                mail.To.Add(emailToAddress);
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = true;
                //mail.Attachments.Add(new Attachment("D:\\TestFile.txt"));//--Uncomment this to send any attachment  
                using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                {
                    smtp.Credentials = new NetworkCredential(emailFromAddress, password);
                    smtp.EnableSsl = enableSSL;

                    mail.Headers.Add("Disposition-Notification-To", emailToAddress);

                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                    try {
                     
                        MXValidate.LoadLicenseKey("aaa-bbb-ccc");
                        aspNetMX.MXValidate mx = new aspNetMX.MXValidate();

                        // your server infos
                        mx.SMTPHello = "smtp.gmail.com";
                        mx.SMTPFrom = emailFromAddress;
                        mx.LogInMemory = true;

                        mx.RecurseMailDomains = true;

                        MXValidateLevel level = mx.Validate("[email protected]");


                        //aspNetMX.MXValidateLevel level = mx.Validate("[email protected]", aspNetMX.MXValidateLevel.Mailbox);

                        if (level == aspNetMX.MXValidateLevel.Mailbox)
                        {
                            // Valid email address.
                        }
                        else
                        {
                            // NOT valid email address.
                        }
                        smtp.Send(mail);
                    
                    }
                    catch (SmtpFailedRecipientsException ex) {
                        for (int i = 0; i < ex.InnerExceptions.Length; i++)
                        {
                            SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                            if (status == SmtpStatusCode.MailboxBusy ||
                                status == SmtpStatusCode.MailboxUnavailable)
                            {
                                Console.WriteLine("Delivery failed - retrying in 5 seconds.");
                                System.Threading.Thread.Sleep(5000);
                                smtp.Send(mail);
                            }
                            else
                            {
                                Console.WriteLine("Failed to deliver message to {0}",
                                    ex.InnerExceptions[i].FailedRecipient);
                            }
                        }
                    }
                    catch (SmtpException e)
                    {
                        Console.WriteLine("Error: {0}", e.StatusCode);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception caught in RetryIfBusy(): {0}",
                                ex.ToString());
                    }
                    Console.WriteLine(mail.DeliveryNotificationOptions);
                }
            }
        }
   }

}

0
On

So i didn't found the answer for this particular scenario but found some different workarounds

 class Program
    {
        static string smtpAddress = "smtp.gmail.com";
    static int portNumber = 587;
    static bool enableSSL = true;
    static string emailFromAddress = "[email protected]"; //Sender Email Address  
    static string password = "password"; //Sender Password  
    static string emailToAddress = "[email protected]"; //Receiver Email Address  
    static string subject = "Hello";
    static string body = "Hello, This is Email sending test using gmail.";
        static void Main(string[] args)
        {
            testValidEmail();
        }
 public static void testValidEmail()
        {
            TcpClient tClient = new TcpClient("gmail-smtp-in.l.google.com", 25);
            string CRLF = "\r\n";
            byte[] dataBuffer;
            string ResponseString;
            NetworkStream netStream = tClient.GetStream();
            StreamReader reader = new StreamReader(netStream);
            ResponseString = reader.ReadLine();
            /* Perform HELO to SMTP Server and get Response */
            dataBuffer = BytesFromString("HELO Shreya" + CRLF);
            netStream.Write(dataBuffer, 0, dataBuffer.Length);
            ResponseString = reader.ReadLine();
            dataBuffer = BytesFromString("MAIL FROM:<MyEmailID>" + CRLF);
            netStream.Write(dataBuffer, 0, dataBuffer.Length);
            ResponseString = reader.ReadLine();
            /* Read Response of the RCPT TO Message to know from google if it exist or not */
            dataBuffer = BytesFromString("RCPT TO:<" + "TESTEmailID" + ">" + CRLF);
            netStream.Write(dataBuffer, 0, dataBuffer.Length);
            ResponseString = reader.ReadLine();
            if (GetResponseCode(ResponseString) == 550)
            {
                Console.Write("Mai Address Does not Exist !<br/><br/>");
                Console.Write("<B><font color='red'>Original Error from Smtp Server :</font></b>" + ResponseString);
            }
            /* QUITE CONNECTION */
            dataBuffer = BytesFromString("QUITE" + CRLF);
            netStream.Write(dataBuffer, 0, dataBuffer.Length);
            tClient.Close();
        }
        private static  byte[] BytesFromString(string str)
        {
            return Encoding.ASCII.GetBytes(str);
        }

        public static  int GetResponseCode(string ResponseString)
        {
            return int.Parse(ResponseString.Substring(0, 3));
        }
       }
}