C#: Send email via SMTP

Saga 431 Reputation points
2020-12-07T18:39:47.367+00:00

Hi all,

I am attempting to develop a process that sends automated notifications via email. For development, and having a gmail account handy, I followed the instructions in this video:

C# SMTP in Action : How to Send Email in C# using Gmail (Aug. 2019)
https://youtu.be/x8TUxgxVJ9U

The problem is that I get an authentication error. I suspect that the problem is stricter security measures by Google. It might even be that Google no longer offers the SMTP functionality to GMail accounts. What SMTP servers do developers use to test their work-in-progress applications? I could search for available SMTP servers, but before I attempt to use one of these I thought I'd ask here.

Thank you. I've included the code that I am using below. Any feedback is welcomed. As usual, thank you for your time. Saga

private void sysSendMail(string sBody, string sSub, string sTo, string sFrom)
{
    //Send email via SMTP.
    SmtpClient Client = new SmtpClient()
    {
        //Using GMail SMTP
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential()
        {
            UserName = GetAcctCredUsr(), //Returns valid Gmail address.
            Password = GetAcctCredPwd()  //Password to access email above. 
        }
    };

    MailAddress FromeMail = new MailAddress(sFrom, "From");
    MailAddress ToeMail = new MailAddress(sTo, "To");

    MailMessage Message = new MailMessage()
    {
        From = FromeMail,
        Subject = sSub,
        Body = sBody
    };

    Message.To.Add(ToeMail);

    try
    {
        Client.Send(Message);
        MessageBox.Show("Email sent!");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error");
    }
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,027 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Cheong00 3,476 Reputation points
    2020-12-08T03:17:27.067+00:00

    Since I see there is no change from Google's official documentation on how to send mail with SMTP, I would suggest you to try change port to 465, or maybe you should try send a email with these username/password on your Outlook or other mail client to verify if the settings works.

    https://support.google.com/a/answer/176600?hl=en
    https://support.google.com/a/answer/100181

    1 person found this answer helpful.
    0 comments No comments

  2. Nitish Kumar 6 Reputation points MVP
    2020-12-08T05:47:22.93+00:00

    Hello,

    There might be couple of reasons for the authentication error.

    If you have enabled 2way authentication and trying to use the same account in smtp then you might get the error.
    Follow this URL: https://support.google.com/mail/answer/7126229?hl=en

    For your second question:
    I use https://mailtrap.io/ in the development. This provides a fake smtp details and much easy to use.

    Here is the code to send emails using SMTP with https://mailtrap.io/ server.

    Here is a model class:

    public class SMTPConfigModel  
        {  
            public string SenderAddress { get; set; }  
            public string SenderDisplayName { get; set; }  
            public string UserName { get; set; }  
            public string Password { get; set; }  
            public string Host { get; set; }  
            public int Port { get; set; }  
            public bool EnableSSL { get; set; }  
            public bool UseDefaultCredentials { get; set; }  
            public bool IsBodyHTML { get; set; }  
      
        }  
    

    Here are the settings from mailtrap:

    "SMTPConfig": {  
        "SenderAddress": "no-reply@myapp.com",  
        "SenderDisplayName": "My Application Team",  
        "UserName": "07xxxxxx2a3d3699",  
        "Password": "ce423xxxxxxxxf90a",  
        "Host": "smtp.mailtrap.io",  
        "Port":587,  
        "EnableSSL": true,  
        "UseDefaultCredentials": true,  
        "IsBodyHTML": true  
      }  
    

    And finally use the following method to send the email using SMTP:

    private async Task SendEmail(UserEmailOptions userEmailOptions)  
    {  
        MailMessage mail = new MailMessage  
        {  
            Subject = userEmailOptions.Subject,  
            Body = userEmailOptions.Body,  
            From = new MailAddress(_smtpConfig.SenderAddress, _smtpConfig.SenderDisplayName),  
            IsBodyHtml = _smtpConfig.IsBodyHTML  
        };  
      
        foreach (var toEmail in userEmailOptions.ToEmails)  
        {  
            mail.To.Add(toEmail);  
        }  
      
        NetworkCredential networkCredential = new NetworkCredential(_smtpConfig.UserName, _smtpConfig.Password);  
      
        SmtpClient smtpClient = new SmtpClient  
        {  
            Host = _smtpConfig.Host,  
            Port = _smtpConfig.Port,  
            EnableSsl = _smtpConfig.EnableSSL,  
            UseDefaultCredentials = _smtpConfig.UseDefaultCredentials,  
            Credentials = networkCredential  
        };  
      
        mail.BodyEncoding = Encoding.Default;  
      
        await smtpClient.SendMailAsync(mail);  
    }  
    

    Here are some important links:
    Create custom SMTP email service in asp.net core
    Send email from asp.net core application using SMTP
    Send dynamic data (placeholders) in email from asp.net core app

    Code Repository on GitHub: https://github.com/webgentle/aspnet-core-mvc

    Kindly accept this answer if this works for you.
    Thank you.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.