简体   繁体   中英

C# WPF - How to send an e-mail (to myself)?

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.

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);
}

//...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM