How can I send an email via Gmail?

Asked

Viewed 16,084 times

12

I want to create an application to send email, I would like to use a Gmail account to send these emails, how can I do that?

3 answers

13


To send emails you need to include

using System.Net;
using System.Net.Mail;

Create an object MailMessage and fill in the properties:

MailMessage mail = new MailMessage();

mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]"); // para
mail.Subject = "Teste"; // assunto
mail.Body = "Testando mensagem de e-mail"; // mensagem

// em caso de anexos
mail.Attachments.Add(new Attachment(@"C:\teste.txt"));

Having the mail object configured, the next step is to create an Smtp client and send the email.

using (var smtp = new SmtpClient("smtp.gmail.com"))
{
    smtp.EnableSsl = true; // GMail requer SSL
    smtp.Port = 587;       // porta para SSL
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // modo de envio
    smtp.UseDefaultCredentials = false; // vamos utilizar credencias especificas

    // seu usuário e senha para autenticação
    smtp.Credentials = new NetworkCredential("[email protected]", "sua senha");

    // envia o e-mail
    smtp.Send(mail);
}

It is also possible to send emails asynchronously, for this you can not use the using, because the smtp can only call Dispose after sending message. For this there is the event SendCompleted.

smtp.SendCompleted += (s, e) =>
{
    // após o envio pode chamar o Dispose
    smtp.Dispose();
};

// envia assíncronamente
smtp.SendAsync(mail, null);
  • 6

    Remember that in the case of Gmail it is possible that even with the correct login and password it gives authorization failure, just generate one for the specific application. Go on Security > App passwords

  • Don, but that’s not a rule.

  • 3

    Who has verification in two steps configured, it is necessary to generate a Senha do Aplicativo and use instead of password of the e-mail. https://security.google.com/settings/security/apppasswords

  • This procedure is only for Gmail ? wanted to use Outlook exchange

  • 1

    @Fabiosouza there you ask a specific question for him. This is about Gmail.

7

A simplified version for sending emails via Gmail:

using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587)
    {
        Credentials = new NetworkCredential("[email protected]", "password"),
        EnableSsl = true
    })
{
    client.Send("[email protected]", "[email protected]", "test", "test");
}

Note that if the Gmail account has double check activated, shall generate a password specifies to be used with your application (and not download/compromise the security of your account).

To do this, go to the section of your account that allows you to generate application-specific passwords (https://myaccount.google.com/apppasswords), generate a new password and use it when building the client.

4

Note: This setting is for gmail, but it also works for other emails, for this you will have to follow the procedure from start to finish.

First, create the class GmailEmailService.cs. By default it will come as follows (it may be that for you to appear different):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MeuProjeto.LocalClasse
{
    public class GmailEmailService
    {

    }
}

Delete the generated content inside the keys of namespace, leaving you like this:

namespace MeuProjeto.LocalClasse
{

}

Inside the keys of namespace paste the following code:

public interface IEmailService
{
    bool SendEmailMessage(EmailMessage message);
}
public class SmtpConfiguration
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string Host { get; set; }
    public int Port { get; set; }
    public bool Ssl { get; set; }
}
public class EmailMessage
{
    public string ToEmail { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
    public bool IsHtml { get; set; }
}
public class GmailEmailService : IEmailService
{
    private readonly SmtpConfiguration _config;
    public GmailEmailService()
    {
        _config = new SmtpConfiguration();
        var gmailUserName = "[email protected]";
        var gmailPassword = "suasenha";
        var gmailHost = "smtp.gmail.com";
        var gmailPort = 587;
        var gmailSsl = true;
        _config.Username = gmailUserName;
        _config.Password = gmailPassword;
        _config.Host = gmailHost;
        _config.Port = gmailPort;
        _config.Ssl = gmailSsl;
    }
    public bool SendEmailMessage(EmailMessage message)
    {
        var success = false;
        try
        {
            var smtp = new SmtpClient
            {
                Host = _config.Host,
                Port = _config.Port,
                EnableSsl = _config.Ssl,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(_config.Username, _config.Password)
            };
            using (var smtpMessage = new MailMessage(_config.Username, message.ToEmail))
            {
                smtpMessage.Subject = message.Subject;
                smtpMessage.Body = message.Body;
                smtpMessage.IsBodyHtml = message.IsHtml;
                smtp.Send(smtpMessage);
            }
            success = true;
        }
        catch (Exception ex)
        {
            //todo: add logging integration
            //throw;
        }
        return success;
    }
}

Above of namespace import using System.Net.Mail; and using System.Net;

Set your email and password in the field (approximately line 35):

 var gmailUserName = "[email protected]";
 var gmailPassword = "suasenha";

ATTENTION FOR IT TO WORK PROPERLY YOU NEED TO DO THESE PROCEDURES:

first LOG IN TO GMAIL, LOG IN TO YOUR ACCOUNT

2nd GMAIL PASSWORD MUST BE STRONG IF IT CANNOT BLOCK SENDING

LOGIN CANNOT BE DONE IN 2 STEPS

fourth YOU NEED TO GIVE GMAIL PERMISSION TO WORK IN LESS SECURE APPLICATIONS (IMAGE BELOW), SO ACCESS THIS LINK AND CLICK ACTIVATE.

inserir a descrição da imagem aqui

OBS: THIS SERVICE WORKS WITH GMAIL, BUT GMAIL MAKES IT POSSIBLE TO USE OTHER E-MAIL PLATFORMS FOR SENDING VIA GMAIL, SO IF YOUR E-MAIL IS DIFFERENT, FOLLOW THESE STEPS:

first AFTER ALL THIS SETUP, ACCESS THIS LINK, OR IN YOUR ACCOUNT, GO TO CONFIGURAÇÕES > CONTAS E IMPORTAÇÕES AND THEN YOU’LL SEE THE FOLLOWING:

inserir a descrição da imagem aqui

CLICK ON ADICIONAR OUTRO ENDEREÇO DE E-MAIL IN THE WINDOW THAT WILL OPEN, ADD YOUR NAME, AND YOUR DESIRED EMAIL, AND FILL IN THE FOLLOWING INFORMATION ACCORDING TO YOUR PROVIDER:

inserir a descrição da imagem aqui

IF YOU SUCCEED, YOUR REGISTERED EMAIL WILL APPEAR BELOW YOUR GMAIL EMAIL.

NOW USE THIS CODE, WHEN IT IS NECESSARY TO SEND SOME E-MAIL (no controller):

    GmailEmailService gmail = new GmailEmailService();
    EmailMessage msg = new EmailMessage();
    msg.Body = mensagem;
    msg.IsHtml = true;
    msg.Subject = "Cadastro Realizado";
    msg.ToEmail = "[email protected]";
    gmail.SendEmailMessage(msg);

It will be necessary to import GmailEmailService

Tip:

The attribute msg.IsHtml allows you to send messages with html attributes, e.g.: <br/>, <b></b>... etc..

Okay, you can take the test that’s working.

  • On less secure apps, it just depends a lot on how the person uses the account. I agree it’s far from ideal, but if it’s basically a google account for email, there’s no serious problem with that. If one uses the same account for other uses, then one is revealing the password for the application, and exposing everything else besides emails. I think it is more the case of a warning in the reply explaining what is at stake.

  • @Bacco The question is that there is the mechanism of application passwords precisely for this case. As the SMTP client does not support Oauth, generating an application password allows the user to revoke the password without having to change the account password .

  • @Omni yes, it’s like what I said in the comment above. If the account is for email, just change the password, IE, no problem the mode of "less secure applications" if it is a very specific scenario. If the account is for other things, then it is opening doors for misuse of the account. In fact I might have missed mentioning that we have 3 scenarios: user and password, Oauth2 in one step, or if there are two, your password solution per application, which are very practical because they look like the user and password method.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.