简体   繁体   English

C#WPF-如何发送电子邮件(给我自己)?

[英]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... 我有两封电子邮件,email1@gmail.com和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 在此处查看更多信息: 通过Gmail在.NET中发送电子邮件

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

//...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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