简体   繁体   English

C#发送邮件应用程序中的身份验证错误

[英]Authentication Error in C# Send Mail App

I'm developing a simple send mail app in C#, using my CMail Server: 我正在使用CMail Server在C#中开发一个简单的发送邮件应用程序:

MailMessage mail = new MailMessage("from@mail.com", "destination@mail.com");
        mail.Subject = "Sub";
        mail.Body = "Hi!";
        SmtpClient smtp = new SmtpClient("MyServer");
        System.Net.NetworkCredential cred = new System.Net.NetworkCredential("user", "pass");
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = cred;
        smtp.Send(mail);

Obviously i ommited my account information, so, this code throws me an Authentication Exception for some reason. 显然,我忽略了我的帐户信息,因此,出于某些原因,此代码引发了身份验证异常。 I first thought that the code was wrong, so i change the info to my gmail account and everything goes fine, with the only SMTP server that i having trouble is with the CMail. 我首先以为代码是错误的,所以我将信息更改为我的gmail帐户,然后一切正常,只有我遇到问题的唯一SMTP服务器与CMail有关。 Is there a problem with .NET and CMail's SMTP ? .NET和CMail的SMTP是否有问题?

Thanks for the help and comments! 感谢您的帮助和评论!

如果您使用的是两步验证,则需要添加应用程序专用密码。

尝试添加:

smtp.EnableSsl = true;

Full work sample 完整的工作样本

public static void sendEmail()
    {
        //for use GMAIL require enable - 
        //https://myaccount.google.com/lesssecureapps?rfn=27&rfnc=1&eid=39511352899709300&et=0&asae=2&pli=1
        Console.WriteLine("START MAIL SENDER");

        //Авторизация на SMTP сервере
        SmtpClient Smtp = new SmtpClient("smtp.gmail.com", 587);
        Smtp.EnableSsl = true;
        Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        Smtp.UseDefaultCredentials = false;
         //username   password
        Smtp.Credentials = new NetworkCredential("rere", "rere");

        //Формирование письма
        MailMessage Message = new MailMessage();
        Message.From = new MailAddress("rere@gmail.com");
        Message.To.Add(new MailAddress("rere@gmail.com"));
        Message.Subject = "test mesage";
        Message.Body = "tttt body";

        string file = "D:\\0.txt";
        if (file != "")
        {
            Attachment attach = new Attachment(file, MediaTypeNames.Application.Octet);
            ContentDisposition disposition = attach.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            Message.Attachments.Add(attach);
            Console.WriteLine("ADD FILE [" + file + "]");
        }
        try
        {
            Smtp.Send(Message);
            MessageBox.Show("SUCCESS");
        }
        catch { MessageBox.Show("WRONG"); }
    }

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

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