Sending email using ASP.NET Core 6.0 Web API

Viewed 236

I am trying to send a email from an ASP.NET Core 6 Web API using gmail account sampleEmail@gmail.com. I noticed that the option to allow less secure apps was no longer available on gmail and whenever I try sending the email it does nothing, but no errors are thrown.

using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyPortfolioWebAPI.Data;
using MyPortfolioWebAPI.Models;
using Microsoft.AspNetCore.Cors;
using System.Text;
using MimeKit;
using MimeKit.Text;
using MailKit.Net.Smtp;
using MailKit.Security;

try
{
    StringBuilder template = new();
    template.AppendLine("from  " + email.EmailAddress);
    template.AppendLine("Name  " + email.Name);
    template.AppendLine(email.Message);

    var Mails = new MimeMessage();
    Mails.From.Add(MailboxAddress.Parse("sampleEmail@gmail.com"));
    Mails.To.Add(MailboxAddress.Parse("thabisofakude40@gmail.com"));
    Mails.Subject = " test response ";
    Mails.Body = new TextPart(TextFormat.Text) { Text = template.ToString() };

    using var smtp = new SmtpClient();
    smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
    smtp.Authenticate("sampleEmail@gmail.com", "Password");

    smtp.Send(Mails);

    smtp.Disconnect(true);
}
catch (Exception ex)
{
    Console.WriteLine(ex);
}

Kindly assist

1 Answers

i got it i just had to enable 2 factor authentification on gmail

Related