I get can error when sending email using mvc 5 - c#

I do not know what I am doing wrong but I want after a user is registered and get an email. I have been following the msdn tutorial and other tutorial and I tried it with different application.
Account Controller
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
user.Email = model.Email;
user.Confirmed = false;
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage(
new System.Net.Mail.MailAddress("21408704#dut4life.ac.za", "Registration"),
new System.Net.Mail.MailAddress(user.Email));
m.Subject = "Confirmation of Email";
m.Body = string.Format("Dear {0} <br/>Thank you please click below: <ahref=\"{1}\" title=\"user Email Confirm\">{1} <\a>", user.UserName, Url.Action
("Confirmed Email", "Accounts", new { Token = user.Id, Email = user.Email }, Request.Url.Scheme));
m.IsBodyHtml = true;
m.BodyEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
smtp.Host = "pod51014.outlook.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("21408704#dut4life.ac.za", "Dut951121");
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
try
{
smtp.Send(m);
}
catch (Exception e)
{
throw e;
}
return RedirectToAction("Confirmed Email", "Accounts", new { Email = user.Email });
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
Register model
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
I get this error after it loads for a long time
Server Error in '/' Application.
Source Error:
Line 180: catch (Exception e)
Line 181: {
Line 182: throw e;
Line 183: }
Line 184:
The operation has timed out.
Exception Details: System.Net.Mail.SmtpException: The operation has timed out.

The problem is with your SMTP client. I think you have to set UseDefaultCredentials before Credentials like below:
SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("21408704#dut4life.ac.za", "Dut951121");
Please let me know if it still doesn't work for you.
Update:
A simple SMTP client would look like below:
using System.Net.Mail;
...
MailMessage mail = new MailMessage("you#yourcompany.com", "user#hotmail.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredentials("user","pass");
client.Host = "smtp.google.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

Related

how to write a simple code that sends email

i developed a simple website that stores in the user name and sends that to my emailid and then downloads a file.File is getting downloaded but not mailing me the username.
try
{
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("mygmailid");
mailMessage.From =new MailAddress("mydomainbasedemailid");
mailMessage.Subject = "ASP.NET e-mail test";
mailMessage.Body = "Hello world,\n\nThis is an ASP.NET test e-mail!";
SmtpClient smtpClient=new SmtpClient("mail.mydomain.com",587);
smtpClient.Send(mailMessage);
Response.Write("E-mail sent!");
}
catch (Exception ex)
{
Response.Write("Could not send the e-mail - error: " + ex.Message);
}
Try to set the Smtp.Credentials like this:
string HOSTLOGIN = "YourHostLogin";
string HOSTPW = "YourTopSecretPasswort";
var credentials =
new System.Net.NetworkCredential() { UserName = HOSTLOGIN, Password = HOSTPW };
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = credentials;
client.EnableSsl = true;

Sending email through Gmail throws an error

Im working on an web application i got stuck between this email sending code.I am working on contact page where anyone can send you email as you guys know that.This code in working fine but i can't pass through this error
as i said im working with Asp.Net Mvc so here is my POST controller im using gmail account so that it won't conflict between any mail services.
public ActionResult sendemail()
{
return View();
}
[HttpPost]
public ActionResult sendemail(string to, string from, string subject, string body, string pwd)
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential("faseehyasin12#gmail.com", pwd);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from);
mail.Subject = subject;
mail.Body = body;
try
{
client.Send(mail);
Response.Write("ok");
return View();
}
catch(Exception e)
{
throw e;
}
}
and here is my view and i want to ask do i really need a password to send email to someone in this code ?
and my GET controller is empty with only written code is return view() so i won't bother to take ss for that. i have also allowed "less secure app" but it still gives me this error. Need Help
First go to https://myaccount.google.com/lesssecureapps and change status as open.
And go to https://accounts.google.com/b/0/displayunlockcaptcha and click Continue button.
Please try with following code.
string host = "smtp.gmail.com";
int port = 587;
bool ssl = true;
string fromAddress = "faseehyasin12#gmail.com";
string fromPassword = "your password here";
using (var mail = new MailMessage())
{
string subject = "Test";
string body = "Mail test";
mail.From = new MailAddress(fromAddress);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
mail.To.Add("mail#domain.com");
using (var smtpServer = new SmtpClient(host,port))
{
smtpServer.UseDefaultCredentials = false;
smtpServer.Credentials = new System.Net.NetworkCredential(fromAddress, fromPassword);
smtpServer.EnableSsl = ssl;
smtpServer.Send(mail);
}
}

Mail sending fails through c# when encryption connection is TLS

I am setting up mail sending in my code as below
NetworkCredential nc = new NetworkCredential(ConfigurationManager.AppSettings["EmailId"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
MailMessage mm = new MailMessage();
mm.From = new MailAddress(SendEmailaddress);
mm.Body = "Test Mail";
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
mm.To.Add(ToEmailAddress);
mm.Subject = "Test";
SmtpClient sp = new SmtpClient();
sp.UseDefaultCredentials = false;
sp.Credentials = nc;
sp.EnableSsl = true;
sp.DeliveryMethod = SmtpDeliveryMethod.Network;
sp.Port = 587
sp.Host = ConfigurationManager.AppSettings["SMTP"].ToString();
sp.Send(mm);
A error is thrown at the time of mail sending. Mail sending works if I configure outlook on the same PC with these settings with TLS as encrypted connnection.
I have checked many posts where it is suggested that EnableSsl = true should be set for TLS to work but it does not work for me. It throws below error
Transaction failed. The server response was: 5.7.1
: Recipient address rejected: Access denied
at System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode
statusCode, String response) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender,
MailAddressCollection recipients, String deliveryNotify,
SmtpFailedRecipientException& exception) at
System.Net.Mail.SmtpClient.Send(MailMessage message)
I have hit a roadblock as no solution is found. is there a setting which needs to be done on server?
protected void SendAlertEmail(string smtpserver, string smtpport, string smtpuser, string smtppass, int ssl, int auth, string subject, string from, string to, string body)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(SplitEmailStrging(from), HttpUtility.HtmlDecode(Request.Form["senderName"]));
string emails = to;
if (emails.Contains(","))
{
string[] emailslist = Regex.Split(emails, #",");
foreach (string email in emailslist)
{
mail.To.Add(SplitEmailStrging(email));
}
}
else
{
if (emails.Contains("<"))
{
mail.To.Add(SplitEmailStrging(emails));
// Response.Write(SplitEmailStrging(emails));
}
else
{
mail.To.Add(emails);
// Response.Write(emails);
}
}
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = HttpUtility.HtmlDecode(body);
SmtpClient client = new SmtpClient(smtpserver);
if (int.Parse(smtpport) == 465)
{
client.Port = 25;
}
else
{
client.Port = int.Parse(smtpport);
}
if (ssl == 1)
{
client.EnableSsl = true;
}
else
{
client.EnableSsl = false;
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpuser, smtppass);
client.UseDefaultCredentials = false;
client.Credentials = credentials;
client.Send(mail);
}
catch (Exception ex)
{
Response.Write("Error: " + ex.InnerException.Message);
Response.End();
}
}

C# Customising MailAddress.From field not working

I am trying to send Emails from my custom address to users using C# and googles smtp service. My problem is that when the when the user receives the message it is displayed admin#customDomain.co.uk <myAddress#gmail.com> in the from section of the email.
My problem is that I want the user to see admin#customDomain.co.uk <admin#customDomain.co.uk>. Is this possible using the google service? Or should I look at some other option? If so what?
I have tried the answers on this thread but non worked and I also found this google blog post but I cant work out how it can solve my issue
My Code
string SmtpAddress = "smtp.gmail.com";
int MyPort = 587;
bool enableSSL = true;
string MyPassword = "somePassword";
string MyUsername = "aUsername";
public string EmailFrom = "admin#customDomain.co.uk";
public string Subject = "Test Subject";
public void Send(string body, BL.Customer customer)
{
using (MailMessage message = new MailMessage())
{
message.To.Add(new MailAddress(customer.EmailAddress));
if (!String.IsNullOrEmpty(customer.SCEmailAddress))
{
//message.To.Add(new MailAddress(customer.SCEmailAddress));
}
message.From = new MailAddress(EmailFrom, EmailFrom);
message.Subject = Subject;
message.Body = string.Format(body);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = MyUsername,
Password = MyPassword
};
smtp.Credentials = credential;
smtp.Host = SmtpAddress;
smtp.Port = MyPort;
smtp.EnableSsl = enableSSL;
try
{
smtp.Send(message);
}
catch (SmtpException se)
{
throw se;
}
}
}
}

Time out error while sending mail to gmail account using smtp port 465 in asp.net

public void SendEmailWithAttachment(string pFrom, string pTo, string pSubject, string pBody, string pServer, string strAttachmentPDFFileNames)
{
try
{
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
string UserName = ConfigurationManager.AppSettings["SMTPUserName"];
string Password = ConfigurationManager.AppSettings["SMTPPassword"];
if (pTo.Contains(","))
{
string[] ToAdd = pTo.Split(new Char[] { ',' });
for (int i = 0; i < ToAdd.Length; i++)
{
Message.To.Add(ToAdd[i]);
}
}
else
{
Message.To.Add(pTo);
}
//System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(pTo);
//Message.To.Add(toAddress);
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress(pFrom);
Message.From = fromAddress;
Message.Subject = pSubject;
Message.Body = pBody;
Message.IsBodyHtml = true;
// Stream streamPDFImages = new MemoryStream(bytPDFImageFile);
//System.Net.Mail.SmtpClient
var smtpClient = new System.Net.Mail.SmtpClient();
{
Message.Attachments.Add(new System.Net.Mail.Attachment(strAttachmentPDFFileNames));
smtpClient.EnableSsl = true;
smtpClient.Host = pServer;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
smtpClient.Port = 465;
smtpClient.Send(Message);
}
}
catch (Exception Exc)
{
Exception ex = new Exception("Unable to send email . Please Contact administrator", Exc);
throw ex;
}
}
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("yourMail", "yourPassword");
smtp.EnableSsl = true;
MailMessage msg = new MailMessage(sendFrom, "yourMail");
msg.ReplyToList.Add(sendFrom);
msg.Subject = subject;
msg.Body = bodyTxt;
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(#"C:\Projects\EverydayProject\test.txt");
msg.Attachments.Add(attachment);
smtp.Send(msg);
Here is working code to send an email to gmail smtp. From what I see you don't set UseDefaultCredentials = false and you are using wrong port. Also you MUST NOT override exceptions like this., throw the initial exception. Also for this to work you need to turn off security setting in your Gmail account. You can google it.

Categories