2

for debugging purposes, I have globally handled all exceptions. Whenever an exception occurs, I silently handle it, and want to send myself an e-mail with the error details, so I can address this issue.

I have two emails, email1@gmail.com, and email2@gmail.com...

I have attempted using this code to send myself an e-mail, but it is not working.

        string to = "email1@gmail.com";
        string from = "email2@gmail.com";
        string subject = "an error ocurred";
        string body = e.ToString();
        MailMessage message = new MailMessage(from, to, subject, body);
        SmtpClient client = new SmtpClient("smtp.google.com");
        client.Timeout = 100;
        client.Credentials = CredentialCache.DefaultNetworkCredentials;
        client.Send(message);

I have tried countless other pieces of code but I have no idea how to do it. Does anyone have a solid solution for this? Thanks a bunch.

A T
  • 185
  • 1
  • 2
  • 12

1 Answers1

3

This has to work. See more info here: Sending email in .NET through Gmail

using System.Net;
using System.Net.Mail;

//...

var fromAddress = new MailAddress("alextodorov01@abv.bg", "From Name");
var toAddress = new MailAddress("kozichka01@abv.bg", "To Name");
const string fromPassword = "fromPassword";
const string subject = "an error ocurred";
const string body = e.ToString();

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

//...
Community
  • 1
  • 1
DDan
  • 7,436
  • 4
  • 29
  • 47
  • One more thing, you need to allow less secure apps to access your account. – Kim Hoang Dec 23 '16 at 01:46
  • 1
    True. You will probably get notification about it though. Log in to your sending gmail account after trying. About Allowing less secure apps to access your account: https://support.google.com/accounts/answer/6010255?hl=en – DDan Dec 23 '16 at 01:49