The SMTP server requires a secure connection or th

2019-07-06 09:17发布

问题:

I'm getting the above error. I've looked at online solutions and I seem to have done all that is necessary but I'm still getting it. I've included Enablessl = true; Delivery method is Network and I've supplied the credentials. I debugged it and the username and password seem to be correct.

using System;
using System.Net;
using System.Net.Mail;
using System.Windows.Forms;

namespace SendMail
{
    public partial class MainWindow : Form
    {
        #region Private variables
        private MailMessage _message = new MailMessage();
        private EmailSender sender = EmailSender.GetInstance();
        private SmtpClient _smtpClient = new SmtpClient();
        #endregion

        public MainWindow()
        {
            InitializeComponent();
        }

        private void PrepareMailMessage()
        {
            // Set the FROM address
            _message.From = new MailAddress(tbFromAddr.ToString().Trim());

            // Set the TO address
            _message.To.Add(new MailAddress(tbToAddr.ToString().Trim()));

            // Set the SUBJECT
            _message.Subject = tbSubject.ToString();

            _message.IsBodyHtml = false;
            _message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
            _message.Priority = MailPriority.High;
            _message.SubjectEncoding = System.Text.Encoding.UTF8;
            _message.BodyEncoding = System.Text.Encoding.UTF8;
        }

        private void PrepareServer()
        {
            _smtpClient.Host = "smtp.gmail.com";
            _smtpClient.Port = 587;
            _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            _smtpClient.UseDefaultCredentials = false;
            _smtpClient.Credentials = new NetworkCredential(tbFromAddr.ToString().Trim(), tbPassword.ToString().Trim());
            _smtpClient.EnableSsl = true;
        }

        private void PrepareSender()
        {
            sender.Message = _message;
            sender.smtpClient = _smtpClient;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            PrepareMailMessage();
            PrepareServer();
            PrepareSender();
            //this.sender.Send();
            _smtpClient.Send(_message);
        }
    }
}

回答1:

I checked your code and it worked for me. However, I am unsure about the purpose of the method PrepareSender(). I included message body(_message.Body) on PrepareMailMessage().

Did you tried using the default credentials?

_smtpClient.UseDefaultCredentials = true