“An attempt was made to access a socket in a way forbidden by its access permissions” while using SMTP

后端 未结 7 1793
灰色年华
灰色年华 2020-11-29 07:19

I am trying to send an SMTP email when certain values in database crosses its threshold value.

I have already allowed ports 25,587 and 465 in the Windows firewall an

7条回答
  •  忘掉有多难
    2020-11-29 08:03

    Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.

    Here is the code - The code is in asp.net core 2.0 but should work in above versions.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using MailKit.Net.Smtp;
    using MimeKit;
    
    namespace UnityAssets.Website.Services
    {
        public class EmailSender : IEmailSender
        {
            public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
            {
                var email = new MimeMessage();
                email.From.Add(new MailboxAddress("Application Name", "applicationId@gmail.com"));
                email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
                email.Subject = subject;
    
                var body = new BodyBuilder
                {
                    HtmlBody = htmlMessage
                };
    
                email.Body = body.ToMessageBody();
    
                using (var client = new SmtpClient())
                {
                    //provider specific settings
                    await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
                    await client.AuthenticateAsync("youremailid@gmail.com", "sketchunity").ConfigureAwait(false);
    
                    await client.SendAsync(email).ConfigureAwait(false);
                    await client.DisconnectAsync(true).ConfigureAwait(false);
                }
            }
        }
    }
    

提交回复
热议问题