简体   繁体   中英

Why is my IP now blocked from sending email via Mailkit from my ASP.NET Core application hosted in Azure?

In my ASP.NET Core web I used authentication for my users. They can reset their password and also receieve confirmation emails when they create an account. To accomplish this I use Mailkit . When I run my application locally, it works fine and can send emails without problems, it used to work when I deployed it to Azure but then stopped one day.

I then received an email failed delivery receipt stating the following:

someuser@hotmail.co.uk: SMTP error from remote server for MAIL FROM command, host: eur.olc.protection.outlook.com (104.47.12.33) reason: 550 5.7.1 Service unavailable, Client host [82.165.159.37] blocked using S pamhaus. To request removal from this list see https://www.spamhaus.or g/query/ip/82.165.159.37 (AS3130). [DB3EUR04FT052.eop-eur04.prod.prote ction.outlook.com]

So, my application has been black listed by https://www.spamhaus.org . The reason given was:

The IP addresses listed in this SBL are used by 1&1 solely for delivering emails that have been internally (by 1&1) classified as SPAM.

I reached out to my service provider and they have no idea what any of this means nor do they know how to unblock anything. So, for reasons of good order I thought it would be a good idea to check over my setup and code to see what I may be doing wrong in this situation and try and fix it. Whilst this may not remove any blacklist, it may help prevent it in the future.

Here is my setup for mailkit, starting with the appsettings. You'll notice I'm using port 465 for sending over SSL which is what I understood was needed.

appsettings.json

{
  "EmailConfiguration": {
    "SmtpServer": "smtp.ionos.co.uk",
    "SmtpPort": 465,
    "SmtpUsername": "myemail@mydomain.co.uk",
    "SmtpPassword": "xxx",

    "PopServer": "pop.ionos.co.uk",
    "PopPort": 993,
    "PopUsername": "myemail@mydomain.co.uk",
    "PopPassword": "xxx"
  },      
  "AllowedHosts": "*"
}

Areas/Pages/Account/Manage/ForgotPassword.cshtml.cs

public async Task<IActionResult> OnPostAsync()
{
    if (ModelState.IsValid)
    {                
        var user = await _userManager.FindByEmailAsync(Input.Email);
        if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
        {
            // Don't reveal that the user does not exist or is not confirmed
            return RedirectToPage("./ForgotPasswordConfirmation");
        }
        var code = await _userManager.GeneratePasswordResetTokenAsync(user);
        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
        var callbackUrl = Url.Page(
            "/Account/ResetPassword",
            pageHandler: null,
            values: new { area = "Identity", code },
            protocol: Request.Scheme);               

            var callbackEncoded = HtmlEncoder.Default.Encode(callbackUrl);
                
            //============================
            // Send email
            //============================
            EmailMessage accountEmail = new EmailMessage
            {
                FromAddresses = {
                    new EmailAddress {
                        Name = "Password Reset",
                        Address = "myemail@mydomain.co.uk" }
                    },
                ToAddresses = {
                    new EmailAddress {
                       Name = Input.Email,
                       Address = Input.Email }
                    },
                    Subject = "Password Reset"
                };

                //Pass to email action
                SendEmail(accountEmail, callbackEncoded);

            return RedirectToPage("./ForgotPasswordConfirmation");
        }    
    return Page();
}

The above code is pretty much OOTB password reset with the inclusion of my mailkit information populated under the 'Send email' comments. From there, the information is passed to my SendEmail() action for processing.

Areas/Pages/Account/Manage/ForgotPassword.cshtml.cs

public void SendEmail(EmailMessage emailMessage, string callbackUrl)
{
    //============================
    // Setup email
    //============================
    var message = new MimeMessage();
        message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
        message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
        message.Subject = emailMessage.Subject;

        //============================
        // Use body builder for HTML and plain text
        //============================
        var builder = new BodyBuilder();

        //============================
        // Embed my logo
        //============================
        var image = builder.LinkedResources.Add(@"wwwroot/images/logo.png");
        image.ContentId = MimeUtils.GenerateMessageId();

        //Set the plain-text version of the email
        builder.TextBody = @"Oops! it looks like you've forgotten your password, you can reset it by clicking on the following link: " + callbackUrl;

        //Set the HTML version of the message
        builder.HtmlBody = string.Format(@"Oops! it looks like you've forgotten your password, you can reset it by clicking on the following link: " + callbackUrl);

        message.Body = builder.ToMessageBody();


        //Be careful that the SmtpClient class is the one from Mailkit not the framework!
        using (var emailClient = new SmtpClient())
        {
            //The last parameter here is to use SSL (Which you should!)
            try
            {
                emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            //Remove any OAuth functionality as we won't be using it. 
            emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

            emailClient.Authenticate(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);
            try
            {
                emailClient.Send(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            emailClient.Disconnect(true);
        }

    }

Is my setup incorrect for what I'm trying to do and is there anyway that I can improve on this? Being black listed is frustrating but I don't understand how I can around it.

Sometimes it happens. You can remove your ip from spamhaus.org by writing them e-mail https://www.spamhaus.org/sbl/query/SBL275659

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