studio - Enviar correo electrónico a través de SMTP utilizando C#
envio de correo electronico c# (17)
No entiendo por qué este código no funciona. Me sale un error diciendo que la propiedad no puede ser asignada
MailMessage mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.To = "[email protected]"; // <-- this one
mail.From = "[email protected]";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
Así es como funciona para mí. Esperamos que te sea útil
MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = "smtp.internal.mycompany.com";
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("user", "Password");
objeto_mail.From = new MailAddress("[email protected]");
objeto_mail.To.Add(new MailAddress("[email protected]"));
objeto_mail.Subject = "Password Recover";
objeto_mail.Body = "Message";
client.Send(objeto_mail);
Esta :
mail.To = "[email protected]";
Debiera ser:
mail.To.Add(new MailAddress("[email protected]"));
Esta respuesta presenta:
- Usando ''usar'' siempre que sea posible (interfaces IDisposable )
- Usando inicializadores de objetos
- Programación asíncrona
- Extraiga SmtpConfig a una clase externa (ajústelo a sus necesidades)
Aquí está el código extraído:
public async Task SendAsync(string subject, string body, string to)
{
using (var message = new MailMessage(smtpConfig.FromAddress, to)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
using (var client = new SmtpClient()
{
Port = smtpConfig.Port,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = smtpConfig.Host,
Credentials = new NetworkCredential(smtpConfig.User, smtpConfig.Password),
})
{
await client.SendMailAsync(message);
}
}
}
Clase SmtpConfig:
public class SmtpConfig
{
public string Host { get; set; }
public string User { get; set; }
public string Password { get; set; }
public int Port { get; set; }
public string FromAddress { get; set; }
}
Esto solo me funcionó a partir de marzo de 2017. Comenzó con la solución anterior "Al fin funcionó :)" que no funcionó al principio.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("<me>@gmail.com", "<my pw>");
MailMessage mm = new MailMessage(from_addr_text, to_addr_text, msg_subject, msg_body);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
Finalmente conseguí trabajar :)
using System.Net.Mail;
using System.Text;
...
// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");
MailMessage mm = new MailMessage("[email protected]", "[email protected]", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
lo siento por la mala ortografía antes
Inicialice MailMessage
con las direcciones de correo electrónico del remitente y el destinatario. Debería ser algo como
string from = "[email protected]"; //Senders email
string to = "[email protected]"; //Receiver''s email
MailMessage msg = new MailMessage(from, to);
Lea el fragmento de código completo de cómo enviar correos electrónicos en c #
MailKit es una biblioteca de cliente de correo .NET multiplataforma de código abierto que se basa en MimeKit y está optimizada para dispositivos móviles. Tiene más funciones avanzadas que System.Net.Mail Microsoft TNEF a través de MimeKit.
Descarga el paquete nuget desde here .
Mira este ejemplo puedes enviar correo.
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(senderName, [email protected]));
mailMessage.Sender = new MailboxAddress(senderName, [email protected]);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.TextBody = "Hello There";
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("[email protected]", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Primero, vaya a https://myaccount.google.com/lesssecureapps y haga que Permitir aplicaciones menos seguras sea verdadero .
Luego use el siguiente código. Este código de abajo solo funcionará si tu dirección de correo electrónico es de gmail.
static void SendEmail()
{
string mailBodyhtml =
"<p>some text here</p>";
var msg = new MailMessage("[email protected]", "[email protected]", "Hello", mailBodyhtml);
msg.To.Add("[email protected]");
msg.IsBodyHtml = true;
var smtpClient = new SmtpClient("smtp.gmail.com", 587); **//if your from email address is "[email protected]" then host should be "smtp.hotmail.com"**
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new NetworkCredential("[email protected]", "password");
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
Console.WriteLine("Email Sended Successfully");
}
Si desea que su correo electrónico y contraseña no aparezcan en su código y desea que el servidor cliente de correo electrónico de su empresa utilice las credenciales de Windows, utilice el siguiente uso.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
Solo necesito probar esto:
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "companyemail";
string password = "password";
string emailTo = "Your email";
string subject = "Hello!";
string body = "Hello, Mr.";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
esto funcionaria tambien ..
string your_id = "[email protected]";
string your_password = "password";
try
{
SmtpClient client = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential(your_id, your_password),
Timeout = 10000,
};
MailMessage mm = new MailMessage(your_iD, "[email protected]", "subject", "body");
client.Send(mm);
Console.WriteLine("Email Sent");
}
catch (Exception e)
{
Console.WriteLine("Could not end email/n/n"+e.ToString());
}
mail.To
y mail.From
son readonly. Moverlos al constructor.
using System.Net.Mail;
...
MailMessage mail = new MailMessage("[email protected]", "[email protected]");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
//Hope you find it useful, it contain too many things
string smtpAddress = "smtp.xyz.com";
int portNumber = 587;
bool enableSSL = true;
string m_userName = "[email protected]";
string m_UserpassWord = "56436578";
public void SendEmail(Customer _customers)
{
string emailID = [email protected];
string userName = DemoUser;
string emailFrom = "[email protected]";
string password = "qwerty";
string emailTo = emailID;
// Here you can put subject of the mail
string subject = "Registration";
// Body of the mail
string body = "<div style=''border: medium solid grey; width: 500px; height: 266px;font-family: arial,sans-serif; font-size: 17px;''>";
body += "<h3 style=''background-color: blueviolet; margin-top:0px;''>Aspen Reporting Tool</h3>";
body += "<br />";
body += "Dear " + userName + ",";
body += "<br />";
body += "<p>";
body += "Thank you for registering </p>";
body += "<p><a href=''"+ sURL +"''>Click Here</a>To finalize the registration process</p>";
body += " <br />";
body += "Thanks,";
body += "<br />";
body += "<b>The Team</b>";
body += "</div>";
// this is done using using System.Net.Mail; & using System.Net;
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text);
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (fuAttachment.HasFile)//file upload select or not
{
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
Response.write("Send Mail");
Ver video: https://www.youtube.com/watch?v=bUUNv-19QAI
Public Function SendEmail(Optional ByVal p_AsHTML As Boolean = False, Optional ByVal p_themEmail As String = "") As Boolean
Dim client As SmtpClient = New SmtpClient ''''("FMSERVER.FMINNOVATIONS.COM.AU")
''Dim fromAddress As MailAddress = New MailAddress(Me.FromEmail, "WSMenterprise")
''Dim toAddress As MailAddress
Try
Dim aMessage As New MailMessage()
''(New MailAddress(Me.FromEmail, "WSMenterprise"), New MailAddress(anAdd))
If _fromAddress IsNot Nothing Then
If _fromName IsNot Nothing Then
aMessage.From = New MailAddress(_fromAddress, _fromName)
Else
aMessage.From = New MailAddress(_fromAddress)
End If
End If
For Each anAdd As String In _To
aMessage.To.Add(New MailAddress(anAdd))
Next
For Each cc As String In _CC
aMessage.CC.Add(New MailAddress(cc))
Next
For Each bcc As String In _BCC
aMessage.Bcc.Add(New MailAddress(bcc))
Next
aMessage.Subject = _Subject
aMessage.IsBodyHtml = p_AsHTML
If _EmailLogo Is Nothing Then
aMessage.Body = _Body
Else
If p_themEmail.ToString().ToLower.Contains("dexus") Then
Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html")
Dim logo As New LinkedResource(_EmailLogo)
logo.ContentId = "Dexuslogo1"
Dim logo1 As New LinkedResource(_EmailLogo1)
logo1.ContentId = "Dexuslogo2"
htmlView.LinkedResources.Add(logo)
htmlView.LinkedResources.Add(logo1)
aMessage.AlternateViews.Add(htmlView)
Else
Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html")
Dim logo As New LinkedResource(_EmailLogo)
logo.ContentId = "companylogo"
htmlView.LinkedResources.Add(logo)
aMessage.AlternateViews.Add(htmlView)
End If
End If
For Each anAttach As Attachment In _Attachments
aMessage.Attachments.Add(anAttach)
Next
If _ReplyTo IsNot Nothing Then aMessage.ReplyToList.Add(New MailAddress(_ReplyTo))
client.Host = "smtpi.cbre.com.au"
client.UseDefaultCredentials = True
client.Send(aMessage)
Catch exRecipUnk As SmtpFailedRecipientException
Return False
Catch exSmtp As SmtpException
''''exSmtp.StatusCode
Return False
Catch ex As Exception
Return False
End Try
Return True
End Function
If p_Gmap_code = "DE" Then
Dim p_Theme As New Theme("Dexus")
Dim passwordlink As String = ""
Dim DexuslogoImage1 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images/Dexus_Notice_Logo.png")
Dim DexuslogoImage2 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images/DexusTenantNotice.png")
passwordlink = "<a href=''" + p_Theme.TenantLoginPage + "?accesstype=email&te=" + a.Encrypt(p_TenantEmail) + "'' target=''_blank''>here.</a><br/>"
bodys += "<div align=''Center''><table border=''0'' cellpadding=''0'' cellspacing=''0''><tr style=''height:50px;''><td width=''623px'' ></td><td valign=''top'' width=''180''><p align=''right''><a href=''http://www.dexus.com/''><img border=''0'' height=''50'' src=cid:Dexuslogo1 width=''174'' alt=''''/></a></p></td></tr><tr><td colspan=''2'' width=''803'' style=''height:25px;''></td></tr> <tr><td width=''623px''><p align=''left'' style=''font-family:Arial;font-size:14pt;''><strong> Your Dexus Response Password is about to expire</strong></p></td>"
bodys += " <td width=''180''><p align=''right'' style=''font-family:Arial;font-size:10pt;''>" + DateTime.Now.ToString("dd/MM/yyyy") + " </p>"
bodys += "</td></tr><tr><td colspan=''2'' width=''803'' style=''height:30px;''> </td></tr> <tr> <td colspan=''2'' width=''803'' style=''font-family:Arial;font-size:10pt;''>"
bodys += "<p>" + wishes + " " + p_TenantName.Trim().ToString() + "</p>"
bodys += "</td></tr><tr><td colspan=''2'' width=''803'' style=''height:25px;''></td> </tr><tr><td colspan=''2'' width=''803'' style=''font-family:Arial;font-size:10pt;''>"
bodys += "Your Dexus Response password is about to expire in " + p_remaindays.ToString() + " days.<br /><br /> To reset your password and update your details, please click " + passwordlink.ToString() + "<br /><br />Please note that if you do not update your password by " + p_date + ",then your account will be set to inactive and you will not be able to access Dexus Response.</br></br>Please contact Dexus Response if you require assistance in accessing the portal.</p></td>" ''edit
bodys += " </tr><tr><td colspan=''2'' width=''803'' style=''height:30px;''></td></tr><tr><td colspan=''2'' width=''803''><table align=''left'' border=''0'' cellpadding=''0'' cellspacing=''0''><tr><td width=''802'' style=''font-family:Arial;font-size:10pt;''><p><strong>Dexus Response</strong></p></td></tr><tr><td width=''802'' style=''font-family:Arial;font-size:10pt;''><p><a href=''mailto:[email protected]''>[email protected]</a> <strong>|</strong> 1300 339 870 <strong>|</strong> <a href=''https://response.dexus.com/''>response.dexus.com</a></p></td></tr></table></td></tr><tr><td colspan=''2'' width=''803'' style=''height:15px;''></td></tr><tr> <td colspan=''2'' width=''803''><p> </p><p><a href=''https://response.dexus.com/'' border=''0'' target=''_blank''><img border=''0'' height=''133''"
bodys += "src=cid:Dexuslogo2 alt='''' width=''800'' /></a></p></td></tr><tr><td colspan=''2'' width=''803'' style=''height:10px;''></td></tr><tr><td colspan=''2'' width=''803'' style=''font-family:Arial;font-size:10pt;''><p><a href=''http://www.dexus.com/who-we-are/terms-and-conditions'' style='' color:#000000;''>Terms and Conditions</a><strong> | </strong><a href=''http://www.dexus.com/who-we-are/privacy-policy'' style='' color:#000000;''> Privacy Policy</a></p></td></tr><tr><td colspan=''2'' width=''803'' style=''height:40px;''></td></tr><tr><td colspan=''2'' width=''803''><p></p></td></tr><tr><td colspan=''2'' width=''803'' style=''height:10px;''></td></tr><tr></tr><tr><td colspan=''2'' width=''803'' style=''height:20px;''></td></tr></table></div>"
email = New Common.Email(emailHeading, bodys, p_Theme.EmailFrom, DexuslogoImage1, DexuslogoImage2)
email.ToEmail = p_TenantEmail
email.SendEmail(True, p_Theme.EmailFrom)
public static void SendMail(MailMessage Message)
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.googlemail.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("[email protected]", "password");
client.Send(Message);
}
smtp.Host = "smtp.gmail.com"; // the host name
smtp.Port = 587; //port number
smtp.EnableSsl = true; //whether your smtp server requires SSL
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
Ir a través de este artículo para más detalles