The SMTP server requires a secure connection or th

2019-07-06 08:53发布

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条回答
我只想做你的唯一
2楼-- · 2019-07-06 09:36

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
查看更多
登录 后发表回答