email function not working after publishing to iis - asp.net

I've published my app and it is now running from IIS. the problem is that the email function in my controller no longer works when running on IIS (the email function does not send email)
I have an email function on my mvc application and when I run it, it does send an email. The problem starts after I've published my app, Its running on IIS now but the email function does not send the email anymore. How do I go about fixing this?
[HttpPost]
public JsonResult SendMailToUser(string lt, string reason, string name, string fr, string ed)
{
bool result = false;
result = SendMail("ntulisakhile8#gmail.com", "Leave Reaquest", "Hi Sensei,<br />I would like to take a " + lt + " leave<br/><strong>From:</strong> " + fr + " <strong>To:</strong> " + ed + " <br/>Reason: " + reason + "<br/>Regards<br/>" + name + "<br/><a href=~/Response.html>Respond</a>");
return Json(result, JsonRequestBehavior.AllowGet);
}
public bool SendMail(string toEmail, string subject, string emailBody)
{
try
{
string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
MailMessage mailMessage = new MailMessage(senderEmail, toEmail, subject, emailBody);
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
client.Send(mailMessage);
return true;
}
catch (Exception ex)
{
return false;
}
}

Related

Check failure response of email

How to check failure response in email send method using Asp.Net.
The Problem is i didn't get the failure exception.
Please suggest better way.
Here is my code, i'm trying to access the email failure exception...
public static bool sendMail(string strTo, string strSubject, string strName, string strbody)
{
try
{
strName = strName == "" ? "Sir/Madam" : ("Dear " + strName + ",");
StringBuilder mailbody = new StringBuilder();
SmtpClient mailClient = null;
MailMessage message = null;
mailClient = new SmtpClient();
message = new MailMessage();
mailClient.Host = ConfigurationManager.AppSettings["SMTP_MAIL_SERVER"];
mailClient.Port = int.Parse(ConfigurationManager.AppSettings["PORT"]);
//network credentials
string strMailUserName = ConfigurationManager.AppSettings["FROM_ADDR"];
string strMailPassword = ConfigurationManager.AppSettings["FROM_ADDR_PASS"];
string strWebSiteURL = ConfigurationManager.AppSettings["LinkTosite"];
mailClient.EnableSsl = true;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strMailUserName, strMailPassword);
mailClient.UseDefaultCredentials = true;
mailClient.Credentials = SMTPUserInfo;
string strFromMail = ConfigurationManager.AppSettings["FROM_ADDR"];
MailAddress fromAddress = new MailAddress(strFromMail, "TEST (Administrator)");
message.From = fromAddress;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;
//to mail address
message.To.Add(strTo);
message.Subject = "ChatOnGo : " + strSubject;
//mailbody.AppendFormat("<link href='" + strWebSiteURL + "admin/css/bestlogin.css' rel='stylesheet' type='text/css' />");
mailbody.AppendFormat("<div class='dlogin_bg'><div class='dlogin_bg_top'></div><div class='dlogin_bg_bottom'><h2>" + strName + "</h2>");
mailbody.AppendFormat(strbody);
mailbody.AppendFormat("<br/><br/><span>Regards,<br /><a href='" + strWebSiteURL + "'>ChatOnGo Admin</a></span></div></div>");
message.Body = mailbody.ToString();
message.IsBodyHtml = true;
mailClient.SendMailAsync(message);
message = null;
mailClient = null;
return true;
}
catch (SmtpFailedRecipientsException ep)
{
Console.WriteLine(ep.Message);
return false;
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
return false;
}
}
I assume you are using gmail to send email.
You should send the email at least once and if the email is not valid you will receive failure notification.
You can create a nightly/hourly job to check these failure emails and mark them as invalid in your database.
Below is the link to read emails programatically :
http://www.aspsnippets.com/Articles/Fetch-and-read-email-messages-with-attachments-from-GMAIL-POP3-mail-server-in-ASPNet.aspx
I hope this helps!
I am not sure but can you try to send mail without Async (SendMailAsync), just try to call normal send method, probably you will get exception details.

How to send emails from my website domain in asp.net

I want to send mail from my website domain(www.sample.com)
I have written below code. It is not returning any error. But it is not sending mail once I uploaded the pages in the server. Once click on email send, it is not getting any error, but not receiving the mail.
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("mail.sample.co.uk", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("smtpuser#sample.co.uk", "pass#123");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = false;
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
//Setting From , To and CC
mail.From = new System.Net.Mail.MailAddress("smtpuser#sample.co.uk", "MyWeb Site");
mail.To.Add(new System.Net.Mail.MailAddress("myemail#gmail.com"));
mail.CC.Add(new System.Net.Mail.MailAddress("myemail1#gmail.com"));
smtpClient.Send(mail);
I am getting the "mailsend" response text in the page once calling the sending method.
Please help
Anjana
The following code works perfect for me. Make sure you have added a mail account on the smtp server and activated it.
private static string EMAIL_SERVER = "mailservername.mydomain.com";
private static string EMAIL_NAME = "myMailAccount#mydomain.com";
private static string EMAIL_PASSWORD = "complex_password123";
private static string EMAIL_SEND_TO = "sample#mail.com";
protected string SendMail()
{
try
{
System.Net.Mail.MailMessage objMM = new System.Net.Mail.MailMessage();
objMM.From = new MailAddress("fromMe#mail.com", "john doe");
objMM.To.Add(new MailAddress(EMAIL_SEND_TO)); //Note: this To a collection
objMM.Subject = "Subject1";
objMM.Body = "Hello world this is my text";
objMM.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(EMAIL_SERVER);
smtp.Credentials = new NetworkCredential(EMAIL_NAME, EMAIL_PASSWORD);
smtp.Send(objMM);
}
catch (Exception e)
{
return "Message can not be send couse of error: " + e.ToString();
}
return "Message is send.";
}

Can't Send Emails From my Website

Here I am in a strange situation. When I send the email from localhost it is working fine but when I upload the page to the server and try to send email, I get the following error
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
I'm displaying the error message in a label for testing purpose and the try is also misplaced I know, I will set it later.
the code I am using is
if (Page.IsValid)
{
try
{
StringBuilder message = new StringBuilder();
message.Append("Hello My Name is ");
message.Append(txtName.Text);
message.AppendLine();
message.AppendLine("My Contact Number " + txtContactNumber.Text.ToString());
message.AppendLine();
message.AppendLine();
message.AppendLine("My Email Id Is " + txtFromEmailAddress.Text.ToString());
message.AppendLine();
message.Append(txtEmailBody.Text);
MailMessage mailMessage = new MailMessage("xxx#gmail.com", "yyy#gmail.com");
mailMessage.Subject = "New Client Query";
mailMessage.Body = message.ToString();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 25);
//smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "xxx#gmail.com",
Password = "password"
};
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
txtContactNumber.Text = "";
txtFromEmailAddress.Text = "";
txtName.Text = "";
txtEmailBody.Text = "";
lblEmailStatus.Text = "Email Sent Successfully.";
lblEmailStatus.ForeColor = System.Drawing.Color.Yellow;
}
catch(Exception ex)
{
lblEmailStatus.Text = ex.Message + " <br> " + ex.Source;
}
}
else
{
lblEmailStatus.Text = "Error! Email Not Sent ";
lblEmailStatus.ForeColor = System.Drawing.Color.Yellow;
}
I have googled for a couple of hours and checked links at this site as well but I still cant figure it out.
Now I request you guys here if any one have any solutions / hint.
Try this
public string SendEmailTest(String EmailMessage, String FromMail, String MailPassword, String MailServer, String To, String CC, String BCC, String DisplayName, String Subject, String Attachment)
{
try
{
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress;
fromAddress = new MailAddress(FromMail);
smtpClient.Host = MailServer;
smtpClient.Port = 25;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(FromMail, MailPassword);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = SMTPUserInfo;
message.From = fromAddress;
message.To.Add(new MailAddress(To, DisplayName));
if (CC != "")
message.CC.Add(new MailAddress(CC, DisplayName));
if (BCC != "")
message.Bcc.Add(new MailAddress(BCC, DisplayName));
message.Subject = Subject;
message.IsBodyHtml = true;
message.Body = EmailMessage;
if (Attachment != "")
message.Attachments.Add(new Attachment(Attachment));
message.Priority = MailPriority.High;
smtpClient.Send(message);
return "SendEmail";
}
catch (Exception ex)
{
return "Email :" + ex;
}
}
i got the reason finally .
the email i was sending emails from was kind of hacked some days before and for the security reasons google team had kind of marked my email as unsecure . i changed the emails address and it is working fine thanks you all.
Based on the Google Gmail Documentation it would appear that the Port should be 587 not 25. I found a few other questions that seem to be related here and here.
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
client.UseDefaultCredentials = false;

LDAP get group names

I am getting "Logon failure: unknown user name or bad password" error when I try to get the groups a user belongs to. User authentication works fine and this is what I can't understand. How can I properly authenticate a user against AD but can't get his group names?
I get user's ID and password. I have a class that deals with authentication.
if ((true == adAuth.IsAuthenticated(sDomain, sID, sPassword)))
{
string sGroups = adAuth.GetGroups();
This is the authentication class:
public class LdapAuthentication
{
string _path;
string _filterAttribute;
public LdapAuthentication(string path)
{
_path = path;
}
public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + "\\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
try {
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if ((result == null)) {
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = Convert.ToString(result.Properties["cn"][0]);
}
catch (Exception ex) {
throw new Exception("Error authenticating user. " + ex.Message);
//return false;
}
return true;
}
public string GetGroups()
{
//DirectorySearcher search = new DirectorySearcher(_path);
// Use following two lines instead of the above to handle cases of authenticatin against an LDAP server other than local AD domain
DirectoryEntry deSearchRoot = new DirectoryEntry(_path);
DirectorySearcher search = new DirectorySearcher(deSearchRoot);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();
try {
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
string dn = null;
int equalsIndex = 0;
int commaIndex = 0;
int propertyCounter = 0;
for (propertyCounter = 0; propertyCounter <= propertyCount - 1; propertyCounter++) {
dn = Convert.ToString(result.Properties["memberOf"][propertyCounter]);
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if ((equalsIndex == -1)) {
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
} catch (Exception ex) {
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}
IsAuthnticated passes and works fine; GetGroups() returns "Error obtaining group names" followed by "Logon failure: unknown user name or bad password" (i.e. the exception in GetGroups()).
It works fine when I run the app from VS but when I publish it (on the same server), it behaves like this.
Any ideas greatly appreciated.
Never mind; operator error. Code works fine.

here is the code am using... but i want to send the html part as email.

i have converted the aspx page to html and hv stored it in a var myPageHTML . here is the code am using... but i want to send the html part as email as an attachment or as the body of the mail. please help.
//this method on providing the url of the webpage copies the image of that webpage.
protected void Button1_Click(object sender, System.EventArgs e)
{
{
WebClient myClient = new WebClient();
string myPageHTML = null;
byte[] requestHTML;
// Gets the url of the page
string currentPageUrl = Request.Url.ToString();
UTF8Encoding utf8 = new UTF8Encoding();
// by setting currentPageUrl to www.yahoo.com it will fetch the source (html)
// of the yahoo.com and put it in the myPageHTML variable.
// currentPageUrl = "http://www.yahoo.com";
requestHTML = myClient.DownloadData("http://localhost:31788");
myPageHTML = utf8.GetString(requestHTML);
Response.Write();
try
{
SendMail();
}
catch (Exception) { }
}
protected void SendMail()
{
var userName = " from email";
var toAddress = YourEmail.Text.ToString();
const string Password = "password";
string subject = YourSubject.Text.ToString();
string body = "From: " + YourName.Text + "\n";
body += "Email: " + YourEmail.Text + "\n";
body += "Subject: " + YourSubject.Text + "\n";
body += "Question: \n" + Comments.Text + "\n";
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "10.238.52.880";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(userName, Password);
smtp.Timeout = 20000;
}
smtp.Send(userName, toAddress, subject, body);
}
}
I believe you should look at below links to have understanding of Mail sending.
http://csharp.net-informations.com/communications/csharp-email-attachment.htm
http://www.codeproject.com/Articles/10828/Sending-Email-with-attachment-in-ASP-NET-using-SMT
You must also check Generate HTML file at runtime and send as email attachment for generating HTML
Happy Coding !!!

Categories

Resources