Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending mail through C# with gmail is not working after deploying to host

I am trying to send mail through Gmail. I am sending mail successfully when I am testing on localhost, but this does not work when I upload it to a web host. I am seeing this type of error:

Request for the permission of type System.Net.Mail.SmtpPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.

Whenever I am using port 25 get this type of error below:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

Below is my code of send email.

MailMessage mail = new MailMessage("[email protected]","[email protected]");

SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");              
mail.Subject = "Any String" 
mail.Body = mailbody;
mail.IsBodyHtml = true;
SmtpServer.Port = 587;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("[email protected]","123");               
SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);

Is there any solution? Please suggest to me!

like image 775
Vishal Parmar Avatar asked Oct 16 '18 06:10

Vishal Parmar


1 Answers

Edit: OP Added extra information crucial to answering this question, but I'm keeping the old answer around as it might still help someone

New Answer: This StackOverflow question already answered this question

OldAnswer: As this StackOverflow answer already answered, you changed the Port on the SMTP Server to 587 instead of its default (25) and this requires elevated permissions causing this error change this:

SmtpServer.Port = 587;

to this:

SmtpServer.Port = 25;

and it should work

Note: When using SSL the port needs to be 443

like image 184
MindSwipe Avatar answered Oct 08 '22 11:10

MindSwipe