net mvc form error enviar credenciales correos correo con asp archivo adjunto c# .net email

mvc - enviar email c# windows form



Enviar correo electrónico usando System.Net.Mail a través de gmail (7)

Quiero enviar un correo electrónico a través del servidor de Gmail. He puesto el siguiente código pero se está atascado durante el envío. Alguna idea, por favor ...

MailMessage mail = new MailMessage(); mail.From = new System.Net.Mail.MailAddress("[email protected]"); //create instance of smtpclient SmtpClient smtp = new SmtpClient(); smtp.Port = 465; smtp.UseDefaultCredentials = true; smtp.Host = "smtp.gmail.com"; smtp.EnableSsl = true; //recipient address mail.To.Add(new MailAddress("[email protected]")); //Formatted mail body mail.IsBodyHtml = true; string st = "Test"; mail.Body = st; smtp.Send(mail);

Xxxx.com es un dominio de correo en las aplicaciones de Google. Gracias...


Establezca smtp.UseDefaultCredentials = false y use smtp.Credentials = new NetworkCredential (gMailAccount, password);


Esto me ha funcionado:

MailMessage message = new MailMessage("[email protected]", toemail, subjectEmail, comments); message.IsBodyHtml = true; try { SmtpClient client = new SmtpClient("smtp.gmail.com", 587); client.Timeout = 2000; client.EnableSsl = true; client.DeliveryMethod = SmtpDeliveryMethod.Network; //client.Credentials = CredentialCache.DefaultNetworkCredentials; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassord"); client.Send(message); message.Dispose(); client.Dispose(); } catch (Exception ex) { Debug.WriteLine(ex.Message); }

PERO (en el momento de escribir esto - Oct 2017)

Debe habilitar "Permitir aplicaciones menos seguras" dentro de la opción "aplicaciones con acceso a la cuenta" en la configuración de seguridad / privacidad de Google "Mi cuenta" ( https://myaccount.google.com )


Me doy cuenta de que esta es una respuesta a una pregunta muy antigua, con muchas otras buenas respuestas. Estoy publicando este código para incluir algunos de los comentarios útiles publicados por otros usuarios, como Usar declaraciones y métodos más nuevos, donde algunas respuestas tienen métodos obsoletos. Este código fue probado y funcionando desde el 11 de julio de 2018.

Si envía a través de su cuenta de GMail, asegúrese de que la opción Permitir menos aplicaciones seguras esté habilitada desde su panel de control.

Código de clase C #:

public class Email { public void NewHeadlessEmail(string fromEmail, string password, string toAddress, string subject, string body) { using (System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage()) { myMail.From = new MailAddress(fromEmail); myMail.To.Add(toAddress); myMail.Subject = subject; myMail.IsBodyHtml = true; myMail.Body = body; using (System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587)) { s.DeliveryMethod = SmtpDeliveryMethod.Network; s.UseDefaultCredentials = false; s.Credentials = new System.Net.NetworkCredential(myMail.From.ToString(), password); s.EnableSsl = true; s.Send(myMail); } } } }

Código de clase VB:

Public Class Email Sub NewHeadlessEmail(fromEmail As String, password As String, toAddress As String, subject As String, body As String) Using myMail As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage() myMail.From = New MailAddress(fromEmail) myMail.To.Add(toAddress) myMail.Subject = subject myMail.IsBodyHtml = True myMail.Body = body Using s As New Net.Mail.SmtpClient("smtp.gmail.com", 587) s.DeliveryMethod = SmtpDeliveryMethod.Network s.UseDefaultCredentials = False s.Credentials = New Net.NetworkCredential(myMail.From.ToString(), password) s.EnableSsl = True s.Send(myMail) End Using End Using End Sub End Class

Uso C #:

{ Email em = new Email(); em.NewHeadlessEmail("[email protected]", "password", "[email protected]", "Subject Text", "Body Text"); }

VB de uso:

Dim em As New Email em.NewHeadlessEmail("[email protected]", "password", "[email protected]", "Subject Text", "Body Text")


Probé el código C # anterior para enviar correos de Gmail a mi identificación corporativa. Al ejecutar la aplicación, el control se detuvo indefinidamente en la sentencia smtp.Send(mail);

Mientras buscaba en Google, encontré un code similar, que funcionó para mí. Estoy publicando ese código aquí.

class GMail { public void SendMail() { string pGmailEmail = "[email protected]"; string pGmailPassword = "GmailPassword"; string pTo = "ToAddress"; //[email protected] string pSubject = "Test From Gmail"; string pBody = "Body"; //Body MailFormat pFormat = MailFormat.Text; //Text Message string pAttachmentPath = string.Empty; //No Attachments System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage(); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendusing", "2"); //sendusing: cdoSendUsingPort, value 2, for sending the message using //the network. //smtpauthenticate: Specifies the mechanism used when authenticating //to an SMTP //service over the network. Possible values are: //- cdoAnonymous, value 0. Do not authenticate. //- cdoBasic, value 1. Use basic clear-text authentication. //When using this option you have to provide the user name and password //through the sendusername and sendpassword fields. //- cdoNTLM, value 2. The current process security context is used to // authenticate with the service. myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //Use 0 for anonymous myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendusername", pGmailEmail); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendpassword", pGmailPassword); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); myMail.From = pGmailEmail; myMail.To = pTo; myMail.Subject = pSubject; myMail.BodyFormat = pFormat; myMail.Body = pBody; if (pAttachmentPath.Trim() != "") { MailAttachment MyAttachment = new MailAttachment(pAttachmentPath); myMail.Attachments.Add(MyAttachment); myMail.Priority = System.Web.Mail.MailPriority.High; } SmtpMail.SmtpServer = "smtp.gmail.com:465"; SmtpMail.Send(myMail); } }


Use el número de puerto 587

Con el siguiente código, funcionará correctamente.

MailMessage mail = new MailMessage(); mail.From = new MailAddress("[email protected]", "Enquiry"); mail.To.Add("[email protected]"); mail.IsBodyHtml = true; mail.Subject = "Registration"; mail.Body = "Some Text"; mail.Priority = MailPriority.High; SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); //smtp.UseDefaultCredentials = true; smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "<my gmail pwd>"); smtp.EnableSsl = true; //smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Send(mail);

Pero, hay un problema con el uso de gmail. El correo electrónico se enviará con éxito, pero la bandeja de entrada del destinatario tendrá la dirección de Gmail en la "dirección de origen" en lugar de la "dirección de origen" mencionada en el código.

Para resolver esto, siga los pasos mencionados en el siguiente enlace.

http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html

antes de seguir todos los pasos anteriores, debe autenticar su cuenta de gmail para permitir el acceso a su aplicación y también a los dispositivos. Verifique todos los pasos para la autenticación de cuenta en el siguiente enlace:

http://karmic-development.blogspot.in/2013/11/allow-account-access-while-sending.html


ActiveUp.Net.Mail.SmtpMessage smtpmsg = new ActiveUp.Net.Mail.SmtpMessage(); smtpmsg.From.Email = "[email protected]"; smtpmsg.To.Add(To); smtpmsg.Bcc.Add("[email protected]"); smtpmsg.Subject = Subject; smtpmsg.BodyText.Text = Body; smtpmsg.Send("mail.test.com", "[email protected]", "user@1234", ActiveUp.Net.Mail.SaslMechanism.Login);


MailMessage mail = new MailMessage(); mail.From = new System.Net.Mail.MailAddress("[email protected]"); // The important part -- configuring the SMTP client SmtpClient smtp = new SmtpClient(); smtp.Port = 587; // [1] You can try with 465 also, I always used 587 and got success smtp.EnableSsl = true; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // [2] Added this smtp.UseDefaultCredentials = false; // [3] Changed this smtp.Credentials = new NetworkCredential(mail.From, "password_here"); // [4] Added this. Note, first parameter is NOT string. smtp.Host = "smtp.gmail.com"; //recipient address mail.To.Add(new MailAddress("[email protected]")); //Formatted mail body mail.IsBodyHtml = true; string st = "Test"; mail.Body = st; smtp.Send(mail);