Monday, July 27, 2009

Mail code not working in Godaddy hosting server

Hi

In one of the site i hosted there is a functionality to submit a business directory form. As soon as the for is submitted there should be a mail send. I used the following C# code which was working fine in my local setup but gave error when i hosted the files.

Code:
MailMessage message = new MailMessage("fauzi@fauzi.com", "fauzi@fauzi.com", "Add Memeber Request", strbody.ToString());
message.IsBodyHtml = true;
SmtpClient emailClient = new SmtpClient("SmtpClientName");
emailClient.UseDefaultCredentials = true;
emailClient.Send(message);

Later I tried with the Code as follows:

Code:
MailMessage message = new MailMessage("FromEmail", "ToEmail", strSubject, strbody.ToString());
message.IsBodyHtml = true;
SmtpClient emailClient = new SmtpClient("smtp.gmail.com",587); //use this PORT!
emailClient.UseDefaultCredentials = true;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
emailClient.EnableSsl = true;
emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
emailClient.Credentials = new NetworkCredential("UserName", "Password");
emailClient.Send(message);

And the error show was:

Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Net.Mail.SmtpPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

This means that your hosting account is set to "Medium Trust, " whereas the script you are using requires "Full Trust," which cannot be granted by the provider.

Solution:

The solution is we need to change the code as recommended by Godaddy support team as follows.

Code:
MailMessage message = new MailMessage("fauzi@fauzi.com", "fauzi@fauzi.com", "Add Memeber Request", strbody.ToString());

message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "relay-hosting.secureserver.net";
smtp.Credentials = new System.Net.NetworkCredential("Username", "Password");
smtp.Send(message);

Reference

Note: Assemblies Needed are: System.Net.Mail; System.Net; And this code may not work in your local machine, saying...

Mailbox name not allowed. The server response was: sorry, relaying denied from your location [IPAddress] (#5.7.1)


Just ignore this because your local anti virus firewall may block this code to run.

It works fine Now on live site :)

Hope It Helps

Regards
Fauzi

No comments: