简体   繁体   中英

Sending mail via gmail from C# is giving an unexpected errors

I am trying to send an e-mail from my c# WinForms application using g-mail SMTP Server. Here is my code:

        string fromEmail = txtFromEmail.Text.Trim();
        string toEmail = txtToEmail.Text.Trim();
        string[] toArray = toEmail.Split(',');

        MailMessage msg = new MailMessage();
        msg.From = new MailAddress(fromEmail);
        for (int i = 0; i <= toArray.Length - 1; i++)
        {
            msg.To.Add(toArray[i]);
        }
        msg.Subject = "Test E-mail";
        msg.Body = "This is a test";
        msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
        msg.HeadersEncoding = Encoding.GetEncoding(1252);
        msg.SubjectEncoding = Encoding.GetEncoding(1252);
        msg.BodyEncoding = Encoding.GetEncoding(1252);

        AlternateView av1 = AlternateView.CreateAlternateViewFromString(msg.Body, null, System.Net.Mime.MediaTypeNames.Text.Html);
        msg.AlternateViews.Add(av1);

        smtp = new SmtpClient();
        smtp.Host = txtSMTPServer.Text.Trim();
        smtp.UseDefaultCredentials = false;

        NetworkCredential cred = new NetworkCredential();

        SecureString ss = new NetworkCredential("", txtSMTPPassword.Text.Trim()).SecurePassword;
        cred.UserName = txtSMTPUsername.Text.Trim();
        cred.SecurePassword = ss;

        smtp.Credentials = cred;
        smtp.EnableSsl = chkEnableSSL.Checked;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.Port = Convert.ToInt16(txtSMTPPort.Text.Trim());
        smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);


        smtp.SendAsync(msg, msg);

I am getting the following error message:

'e.Error.InnerException.Message' threw an exception of type 'System.NullReferenceException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2147467261
HelpLink: null
InnerException: null
Message: "Object reference not set to an instance of an object."
Source: "8a9e67622e334c659c856a023d4b1631"
StackTrace: "   at <>x.<>m0(frmSettings <>4__this, Object sender, AsyncCompletedEventArgs e)"
TargetSite: {System.String <>m0(Ariba.frmSettings, System.Object, System.ComponentModel.AsyncCompletedEventArgs)}

I am able to send e-mail with a non-Gmail SMTP server. What am I missing?

I have since changed my send method to synchronous using smtp.Send(msg), but now I am getting a different error:

{"Unable to read data from the transport connection: net_io_connectionclosed."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146232800
HelpLink: null
InnerException: null
Message: "Unable to read data from the transport connection: net_io_connectionclosed."
Source: "System"
StackTrace: "   at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)\r\n   at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)\r\n   at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)\r\n   at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)\r\n   at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)\r\n   at System.Net.Mail.SmtpClient.GetConnection()\r\n   at System.Net.Mail.SmtpClient.Send(MailMessage message)"
TargetSite: {Int32 ProcessRead(Byte[], Int32, Int32, Boolean)}

I realize this will probably get tagged as duplicate again, since this was probably asked before, but nothing I have read will solve my problem.

BTW: I have set my Google settings to allow unsecure apps.

We see the real error is here:

net_io_connectionclosed

This means GMail reject your connection.

This is expected.
GMail no longer accepts regular authentication for SMTP connections by default!
It hasn't for a few years now.

If you want to use an GMail as a traditional SMTP server, you must do one of three things:

  1. Enable 2-Factor authentiation and set up a Per-App Password

or

  1. Support OAuth authentication

or

  1. Enable Less Secure Apps

If you don't do one of those things, GMail will reject your SMTP connections.

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