A enviar o e-mail in.NET através do Gmail
em vez de depender do meu servidor para enviar e-mail, estava a pensar em enviar as mensagens de E-mail usando a minha conta do Gmail. Os e-mails são e-mails personalizados para as bandas que toco no meu programa. É possível?
22 answers
Não se esqueça de utilizar System.Net.Mail
, não o System.Web.Mail
desactualizado. Fazer SSL com System.Web.Mail
é uma grande confusão de extensões hacky.
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
DeliveryMethod = SmtpDeliveryMethod.Network
ou ele vai voltar com um" Cliente não foi autenticado " erro. Também é sempre uma boa ideia fazer um intervalo.
Código revisto:
using System.Net.Mail;
using System.Net;
var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "password";
const string subject = "test";
const string body = "Hey now!!";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Para as outras respostas funcionarem "a partir de um servidor" primeiro liguem o acesso para aplicações menos seguras na conta do gmail.
Parece que o google mudou recentemente a sua política de segurança. A resposta nominal de topo já não funciona, até que mude a configuração da sua conta como descrito aqui: https://support.google.com/accounts/answer/6010255?hl=en-GBA partir de Março de 2016, o google mudou o local de configuração novamente!
Http://www.systemnetmail.com/ é provavelmente o site mais absurdamente completo dedicado a umúnico . net namespace...mas tem tudo o que você poderia querer saber sobre o envio de correio via. net, seja ele ASP.NET ou Desktop.
http://www.systemwebmail.com/ foi o URL original no post, mas não deve ser usado para.NET 2.0 ou acima.
Isto é para enviar e-mail com anexação.. Simples e curto..
Fonte: http://coding-issues.blogspot.in/2012/11/sending-email-with-attachments-from-c.html
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your [email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your [email protected]", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
O Google pode bloquear as tentativas de alguns aplicativos ou dispositivos que não utilizam padrões de segurança modernos. Uma vez que estes aplicativos e dispositivos são mais fáceis de invadir, bloqueá-los ajuda a manter a sua conta mais segura.
Alguns exemplos de aplicações que não suportam as mais recentes normas de segurança incluem:
- a aplicação de correio no seu iPhone ou iPad com iOS 6 ou menos
- a aplicação de E-Mail no seu Windows phone antes da versão 8.1
Alguns clientes de Desktop mail como Microsoft Outlook e Mozilla Thunderbird
Portanto, você tem que ativar sinal menos seguro em na sua conta google.
Depois de assinar na Conta google, vá para:
Https://myaccount.google.com/lesssecureapps
ou
https://www.google.com/settings/security/lesssecureapps
Em C#, pode usar o seguinte código:
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Hello World";
mail.Body = "<h1>Hello</h1>";
mail.IsBodyHtml = true;
mail.Attachments.Add(new Attachment("C:\\file.zip"));
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
smtp.Credentials = new NetworkCredential("[email protected]", "password");
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
Aqui está a minha versão: " envie um e-mail em C # usando o Gmail".
using System;
using System.Net;
using System.Net.Mail;
namespace SendMailViaGmail
{
class Program
{
static void Main(string[] args)
{
//Specify senders gmail address
string SendersAddress = "[email protected]";
//Specify The Address You want to sent Email To(can be any valid email address)
string ReceiversAddress = "[email protected]";
//Specify The password of gmial account u are using to sent mail(pw of [email protected])
const string SendersPassword = "Password";
//Write the subject of ur mail
const string subject = "Testing";
//Write the contents of your mail
const string body = "Hi This Is my Mail From Gmail";
try
{
//we will use Smtp client which allows us to send email using SMTP Protocol
//i have specified the properties of SmtpClient smtp within{}
//gmails smtp server name is smtp.gmail.com and port number is 587
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(SendersAddress, SendersPassword),
Timeout = 3000
};
//MailMessage represents a mail message
//it is 4 parameters(From,TO,subject,body)
MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
/*WE use smtp sever we specified above to send the message(MailMessage message)*/
smtp.Send(message);
Console.WriteLine("Message Sent Successfully");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
// Include this.
using System.Net.Mail;
string fromAddress = "[email protected]";
string mailPassword = "*****"; // Mail id password from where mail will be sent.
string messageBody = "Write the body of the message here.";
// Create smtp connection.
SmtpClient client = new SmtpClient();
client.Port = 587;//outgoing port for the mail.
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(fromAddress, mailPassword);
// Fill the mail form.
var send_mail = new MailMessage();
send_mail.IsBodyHtml = true;
//address from where mail will be sent.
send_mail.From = new MailAddress("[email protected]");
//address to which mail will be sent.
send_mail.To.Add(new MailAddress("[email protected]");
//subject of the mail.
send_mail.Subject = "put any subject here";
send_mail.Body = messageBody;
client.Send(send_mail);
Inclui isto,
using System.Net.Mail;
E depois,
MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = Convert.ToInt16("587");
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");
client.EnableSsl = true;
client.Send(sendmsg);
Origem : enviar um e-mail ASP.NET C#
Abaixo está um código de trabalho de exemplo para enviar em um e-mail usando C#, no exemplo abaixo eu estou usando o servidor smtp do google.
O código é bastante auto-explicativo, substitua e-mail e senha com os seus valores de E-mail e senha.
public void SendEmail(string address, string subject, string message)
{
string email = "[email protected]";
string password = "put-your-GMAIL-password-here";
var loginInfo = new NetworkCredential(email, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress(address));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
Se quiser enviar um e-mail de fundo, por favor faça o seguinte
public void SendEmail(string address, string subject, string message)
{
Thread threadSendMails;
threadSendMails = new Thread(delegate()
{
//Place your Code here
});
threadSendMails.IsBackground = true;
threadSendMails.Start();
}
E adicionar espaço de nomes
using System.Threading;
Por aqui
MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = Convert.ToInt32("587");
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("[email protected]","MyPassWord");
client.Send(sendmsg);
Não te esqueças disto:
using System.Net;
using System.Net.Mail;
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("[email protected]");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Mudar o remetente no Gmail / Outlook.com email:
Para evitar o spoofing-Gmail/Outlook.com não o permite enviar a partir de um nome arbitrário de conta de utilizador.
Se tiver um número limitado de remetentes, pode seguir estas instruções e, em seguida, definir o campo From
para este endereço: enviando correio de um endereço diferente
Se você está querendo enviar de um endereço de E-mail arbitrário (como um formulário de feedback no site onde o usuário entra em seu e-mail e você não o melhor que podes fazer é isto:
msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));
Isto permitir-lhe-ia apenas carregar em 'reply' na sua conta de E-mail para responder ao fã da sua banda numa página de feedback, mas eles não obteriam o seu e-mail real, o que provavelmente levaria a uma tonelada de spam.
Se você está em um ambiente controlado isso funciona muito bem, mas por favor note que eu vi alguns clientes de E-mail Enviar para o endereço de from mesmo quando a resposta é especificada (eu não sei qual).
Eu tinha o mesmo problema, mas foi resolvido indo para as configurações de segurança do gmail e permitindo aplicativos menos seguros. O código de Domenic & Donny funciona, mas só se você ativou essa configuração
Se estiver assinado em (para o Google), pode seguir este link e comutar "ligar" para "Acesso para aplicações menos seguras"
using System;
using System.Net;
using System.Net.Mail;
namespace SendMailViaGmail
{
class Program
{
static void Main(string[] args)
{
//Specify senders gmail address
string SendersAddress = "[email protected]";
//Specify The Address You want to sent Email To(can be any valid email address)
string ReceiversAddress = "[email protected]";
//Specify The password of gmial account u are using to sent mail(pw of [email protected])
const string SendersPassword = "Password";
//Write the subject of ur mail
const string subject = "Testing";
//Write the contents of your mail
const string body = "Hi This Is my Mail From Gmail";
try
{
//we will use Smtp client which allows us to send email using SMTP Protocol
//i have specified the properties of SmtpClient smtp within{}
//gmails smtp server name is smtp.gmail.com and port number is 587
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(SendersAddress, SendersPassword),
Timeout = 3000
};
//MailMessage represents a mail message
//it is 4 parameters(From,TO,subject,body)
MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
/*WE use smtp sever we specified above to send the message(MailMessage message)*/
smtp.Send(message);
Console.WriteLine("Message Sent Successfully");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
public static string SendEmail(string To, string Subject, string Msg, bool bodyHtml = false, bool test = false, Stream AttachmentStream = null, string AttachmentType = null, string AttachmentFileName = null)
{
try
{
System.Net.Mail.MailMessage newMsg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["mailCfg"], To, Subject, Msg);
newMsg.BodyEncoding = System.Text.Encoding.UTF8;
newMsg.HeadersEncoding = System.Text.Encoding.UTF8;
newMsg.SubjectEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
if (AttachmentStream != null && AttachmentType != null && AttachmentFileName != null)
{
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentStream, AttachmentFileName);
System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
disposition.FileName = AttachmentFileName;
disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;
newMsg.Attachments.Add(attachment);
}
if (test)
{
smtpClient.PickupDirectoryLocation = "C:\\TestEmail";
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
}
else
{
//smtpClient.EnableSsl = true;
}
newMsg.IsBodyHtml = bodyHtml;
smtpClient.Send(newMsg);
return SENT_OK;
}
catch (Exception ex)
{
return "Error: " + ex.Message
+ "<br/><br/>Inner Exception: "
+ ex.InnerException;
}
}
E a secção correspondente na web.configuração:
<appSettings>
<add key="mailCfg" value="[email protected]"/>
</appSettings>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="[email protected]">
<network defaultCredentials="false" host="mail.exapmple.com" userName="[email protected]" password="your_password" port="25"/>
</smtp>
</mailSettings>
</system.net>
O problema para mim era que a minha palavra-passe tinha um blackslash "\"nele, que copiei colado sem perceber que causaria problemas.
public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)
{
MailMessage mailMessage = new MailMessage();
MailAddress mailAddress = new MailAddress("[email protected]", "Sender Name"); // [email protected] = input Sender Email Address
mailMessage.From = mailAddress;
mailAddress = new MailAddress(receiverEmail, ReceiverName);
mailMessage.To.Add(mailAddress);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
SmtpClient mailSender = new SmtpClient("smtp.gmail.com", 587)
{
EnableSsl = true,
UseDefaultCredentials = false,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("[email protected]", "pass") // [email protected] = input sender email address
//pass = sender email password
};
try
{
mailSender.Send(mailMessage);
return true;
}
catch (SmtpFailedRecipientException ex)
{ }
catch (SmtpException ex)
{ }
finally
{
mailSender = null;
mailMessage.Dispose();
}
return false;
}
Copiando de outra resposta, os métodos acima funcionam, mas o gmail sempre substitui o" de "e" resposta para " E-mail com a conta de envio actual do gmail. aparentemente há um trabalho em torno de:
Http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html
"3. Na página Contas, carregue no link "adicione outro endereço de E-mail que possui" e depois verifique-o "
Ou possivelmente isto
Actualização 3: Leitor Derek Bennett diz: "a solução é ir para as configurações do gmail: contas e "fazer default" uma conta diferente da sua conta do gmail. Isto fará com que o gmail reescreva o campo de From com qualquer que seja o endereço de E-mail da conta por omissão."