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?
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?
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 set up, 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);
}
You can also send emails asynchronously, so you can not use using
, as smtp can only call Dispose
after sending a 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);
A simplified version to send emails through 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");
}
Please note that if your GMail account has two-step verification enabled, you should generate a password specifies to be used with your application (and does not lower / compromise security of your account).
To do this, visit the section of your account that allows you to generate application specific passwords ( link ), generate a new one password and use it when building the client.
Note: This setting is for gmail, but it works for other emails as well, so 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 look different to you):
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 it like this:
namespace MeuProjeto.LocalClasse
{
}
Within 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;
}
}
Up of namespace
amount 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";
WARNING TO HOW IT WORKS YOU MUST DO THESE PROCEDURES:
1st ACCESS GMAIL, ENTER YOUR ACCOUNT
2nd GMAIL PASSWORD MUST BE STRONG, IF IT CAN NOT BLOCK THE SHIPPING
3rd LOGIN CAN NOT BE MADE IN 2 STAGES
4th NEED TO GIVE PERMISSION TO GMAIL TO WORK ON LESS INSURED APPLICATIONS (IMAGE BELOW) TO ACCESS THIS LINK AND CLICK TO ENABLE.
NOTE:THISSERVICEWORKSWITHGMAIL,BUTGMAILPOSSIBILATESTHEUSEOFOTHEREMAILPLATFORMSFORSENDINGTHROUGHTHEGMAIL,SOIFYOUREMAILISDIFFERENT,FOLLOWTHESESTAGES:
1stAFTERALLTHISCONFIGURATION,ACCESSTHIS LINK , OR AT YOUR ACCOUNT, GO TO CONFIGURAÇÕES
> CONTAS E IMPORTAÇÕES
AND THEN YOU WILL SEE THE FOLLOWING:
CLICKAS%WITHTHEWINDOWTHATYOUWILLOPEN,ADDYOURNAME,ANDTHEDESIREDEMAIL,ANDCOMPLETETHEINFORMATIONTOBEFOLLOWEDACCORDINGTOYOURPROVIDER:
IFYOUHAVESUCCESS,YOURE-MAILREGISTEREDBELOWYOURGMAILE-MAIL.
NOWUSETHISCODE,WHENNECESSARYTOSENDANYEMAIL(ADICIONAROUTROENDEREÇODEE-MAIL
):
GmailEmailServicegmail=newGmailEmailService();EmailMessagemsg=newEmailMessage();msg.Body=mensagem;msg.IsHtml=true;msg.Subject="Cadastro Realizado";
msg.ToEmail = "[email protected]";
gmail.SendEmailMessage(msg);
You will need to import no controller
Tip:
The GmailEmailService
attribute allows you to send messages with html attributes, eg msg.IsHtml
, <br/>
... etc.
SOON, YOU CAN DO THE TEST THAT WILL BE WORKING.