Sending email through Gmail throws an error - c#

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);
}
}

Related

Why do I get an error by trying to send a mail with c#?

I'm trying to send an e-mail using C#, but I get this recurring error :
.
Can you explain me what's wrong with my code ?
Here it is :
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.Timeout = 100000;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("myEmailAdress#gmail.com", "myPassword");
MailMessage msg = new MailMessage();
msg.To.Add("receiver#gmail.com");
msg.From = new MailAddress("sender#gmail.com");
msg.Subject = "My subject";
msg.Body = "My body";
client.Send(msg);
MessageBox.Show("Message sent !");
I have encountered same before.
You are getting this error because you haven't set ON on Less secure app access for sender#gmail.com as you are using Gmail SMTP port.
Reason:
Your email has no remotely access permission. You have to configure
it. Suppose you want to sent email from sender#gmail.com so you
have set that permission NO to this account.
How To Set:
You could try like below
Or can open that tab from this link directly Less secure app access
Update:
As per your comment this is for you which has working perfectly since the beginning of my career
public object SendMail(string fromEmail, string toEmail, string mailSubject, string mailBody, string senderName, string senderPass, string attacmmentLocationPath)
{
try
{
MailMessage mail = new MailMessage();
//Must be change before using
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(fromEmail);
mail.To.Add(toEmail);
mail.Subject = mailSubject;
mail.Body = mailBody;
mail.IsBodyHtml = true;
// mail.Attachments.Add(new Attachment(#attacmmentLocationPath));
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(senderName, senderPass);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
return true;
}
catch (Exception ex)
{
return ex;
}
}
Hope that would help.
This code works for gmail, it is very similar to yours with slight differences, but if you try this, and it doesn't work for you, the issue is not the code - perhaps some other network related issue that you are going to need to fix first:
using (var msg = new MailMessage())
{
msg.From = new MailAddress("fromaddress#gmail.com");
msg.To.Add("toaddress#gmail.com");
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("xxx#gmail.com","password");
smtp.Send(msg);
}
}
An SMTP client may log in using an authentication mechanism chosen among those supported by the SMTP servers.

null value when sending email via MVC ASP.NET

I have this MVC C# App and a controller where trying to send a email, but I always got this error
this is the code in my action´controller, it doesn´t receive any model so I add specific values
[HttpPost]
public ActionResult Index2()
{
try
{
MailMessage mail = new MailMessage();
mail.To.Add("valid_email#hotmail.com");
mail.From = new MailAddress("valid_email#gmail.com");
mail.Subject = "PruebaMVC";
string Body = "PruebaMVC";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("valid_email#gmail.com", "correctPWD");
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch (Exception ex)
{
throw new ArgumentNullException("Exception in sendEmail:" + ex.Message);
}
return View();
}
could you please tell what is wrong?
edit: this is the exception I got
As i have used below code and it's working fine for me and i have configured smtp in web.config
ContentType HTMLType = new ContentType("text/html");
NetworkCredential cred = new NetworkCredential(StringConstant.NetworkUserName, StringConstant.NetworkPwd);
MailMessage msg = new MailMessage();
msg.BodyEncoding = System.Text.Encoding.Default;
msg.To.Add(ToEmail);
msg.Priority = System.Net.Mail.MailPriority.High;
msg.Subject = Subj;
msg.Body = strBody;
msg.IsBodyHtml = true;
if (attachement != null)
{
msg.Attachments.Add(attachement);
}
System.Net.Mail.AlternateView HTMLView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(strBody, HTMLType);
msg.From = new MailAddress(StringConstant.MailFrom); // Your Email Id
SmtpClient client = new SmtpClient(StringConstant.SmtpFrom, StringConstant.SmtpPort);
client.Credentials = cred;
client.EnableSsl = true;
client.Send(msg);

How can I use Google to send email? [duplicate]

I am getting an error when trying to send an e-mail through my web service. I have tried enabling access to less secure apps disabling 2-step verification and logging into the account via a web browser. None of the solutions on SO have worked for me. I am still getting:
Error: System.Net.Mail.SmtpException: The SMTP server requires a
secure connection or the client was not authenticated. The server
response was: 5.5.1 Authentication Required.
What can I do to fix this issue?
namespace EmailService
{
public class Service1 : IService1
{
public string SendEmail(string inputEmail, string subject, string body)
{
string returnString = "";
try
{
MailMessage email = new MailMessage();
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
// set up the Gmail server
smtp.EnableSsl = true;
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
// draft the email
MailAddress fromAddress = new MailAddress("cse445emailservice#gmail.com");
email.From = fromAddress;
email.To.Add(inputEmail);
email.Subject = body;
email.Body = body;
smtp.Send(email);
returnString = "Success! Please check your e-mail.";
}
catch(Exception ex)
{
returnString = "Error: " + ex.ToString();
}
return returnString;
}
}
}
Just Go here : Less secure apps , Log on using your Email and Password which use for sending mail in your c# code , and choose Turn On.
Also please go to this link and click on Continue Allow access to your Google account
also I edit it little bit :
public string sendit(string ReciverMail)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("YourMail#gmail.com");
msg.To.Add(ReciverMail);
msg.Subject = "Hello world! " + DateTime.Now.ToString();
msg.Body = "hi to you ... :)";
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential("YourMail#gmail.com", "YourPassword");
client.Timeout = 20000;
try
{
client.Send(msg);
return "Mail has been successfully sent!";
}
catch (Exception ex)
{
return "Fail Has error" + ex.Message;
}
finally
{
msg.Dispose();
}
}
If the above code don't work , try to change it like the following code :
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("YourMail#gmail.com", "YourPassword");

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;
}
}
}
}

Error on sending email from C# code

When I send mail to my gmail account, it shows below error.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Authentication required...
code I am using is below
MailMessage m = new MailMessage();
SmtpClient sc = new SmtpClient();
try
{
m.From = new MailAddress("me#gmail.com");
m.To.Add("me#gmail.com");
m.Subject = "This is a Test Mail";
m.IsBodyHtml = true;
m.Body = "test gmail";
sc.Host = "smtp.gmail.com";
sc.Port = 587;
sc.Credentials = new System.Net.NetworkCredential("me#gmail.com", "passward");
sc.UseDefaultCredentials = true;
sc.EnableSsl = true;
sc.Send(m);
Response.Write("Email Send successfully");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Just tried your code, had to fiddle with a couple things but was sent this. Funny because I have done this previously using Gmail smtp (couple years back). But it looks like they are now verifying apps that use their platform.
Either use another smtp server that you are signed up to, or use your own. (there must be a test one that is available online??). Pretty sure sendgrid do a free trial.
using System.Net;
using System.Net.Mail;
string smtpAddress = "smtp.mail.yahoo.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "email#yahoo.com";
string password = "abcdefg";
string emailTo = "someone#domain.com";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
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.
mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
Please try this this should work for you
Thank you

Categories