Error in sending email through asp.net - asp.net

I'm currently working on a asp.net website using Visual Studio 2010... I'm trying to send email from my contact us page... I'm getting this error:
Warning 9 CA2000 : Microsoft.Reliability :
In method 'Default2.Button1_Click(object, EventArgs)',
call System.IDisposable.Dispose on object 'msg'
before all references to it are out of scope.
c:\Users\toshiba\Documents\Visual Studio 2010\WebSites\Carp-MacDental\ContactUs.aspx.cs 29
C:\...\Carp-MacDental\
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
public partial class Default2 : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string url = Request.Url.AbsoluteUri;
string hyperlink = "<a href='" + url + "'>" + url + "</a>";
NetworkCredential loginInfo = new NetworkCredential("Site#gmail.com", "password");
MailMessage msg = new MailMessage();
msg.From = new MailAddress("Site#gmail.com");
msg.To.Add(new MailAddress(txtEmail.Text));
msg.Bcc.Add(new MailAddress("Site#gmail.com"));
msg.Subject = "Notification from:" + url;
msg.Body = "A message form," + txtName.Text + ", <br/>" + txtMessage.Text;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
lblMessage.Text = "Thank you for contacting us.. we will get back to you as soon as we read your message";
}
}
Its my first time working with this so I'm pretty confused.. Also my mail message that was supposed to be sent through the website wasn't sent...

As Aristos indicated with his link to Msdn, the warning you see is a code analysis warning. Visual Studio has identified that there is a small problem with your code and shows the warning to alert you about the problem.
The problem is that you are creating a couple of instances of classes that implement the IDisposable interface. Classes that implement this interface have a Dispose method that should be called when you are finished with the instance. The Dispose method is used to clean up unmanaged resources that the instance is using behind the scene, thus making sure that memory and other unmanaged resources are freed up for use by other processes.
Both MailMessage and SmtpClient implement this interface. So intances of these classes should have their respective Dispose method called before they go out of scope. The first thought might be to simply add a couple of lines to you existing code:
...
client.Send(msg);
msg.Dispose();
client.Dispose();
...
But a better soultion would probably be to wrap these in using() { } blocks. Doing this will make the compiler insert code that automatically calls the Dispose method, and it will even be called even if there is an exception thrown from inside the using() { } block. Try this:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string url = Request.Url.AbsoluteUri;
string hyperlink = "<a href='" + url + "'>" + url + "</a>";
NetworkCredential loginInfo = new NetworkCredential("Site#gmail.com", "password");
using(MailMessage msg = new MailMessage())
using(SmtpClient client = new SmtpClient("smtp.gmail.com"))
{
msg.From = new MailAddress("Site#gmail.com");
msg.To.Add(new MailAddress(txtEmail.Text));
msg.Bcc.Add(new MailAddress("Site#gmail.com"));
msg.Subject = "Notification from:" + url;
msg.Body = "A message form," + txtName.Text + ", <br/>" + txtMessage.Text;
msg.IsBodyHtml = true;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
lblMessage.Text = "Thank you for contacting us.. we will get back to you as soon as we read your message";
}
That should hopefully get rid of the compiler warning for you. The fact that the email is not really sent is another matter. I cannot help with that without a lot more details. If you need help with that, I suggest you post a new question and add as much info about the problem as possible in that question.

Related

Sending Mail while running the application in IIS

protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(txtEmail.Text.ToString());
mailMessage.Subject = txtSubject.Text.ToString();
mailMessage.To.Add(new MailAddress("my#gmail.com"));
mailMessage.Body = txtSuggestion.Text.ToString();
mailMessage.IsBodyHtml = true;
SmtpClient sc = new SmtpClient();
sc.Host = "smtp.gmail.com";
sc.Port = 587;
sc.Credentials = new NetworkCredential(txtEmail.Text.ToString(), txtPassword.Text.ToString());
sc.EnableSsl = true;
sc.Send(mailMessage);
lblMessage.Text = "Message Sent Successfully";
txtSubject.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtSuggestion.Text = "";
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
This is the code i am using to send email but whenever i am trying to run the application, i am getting error.
enter image description here
if someone can help why i am getting the error, that would be great.
When using SSL, try using port 465.
https://support.google.com/a/answer/176600
You also have another issue with that code that's un-related to the one you're subscribing. When setting up contact us forms, using the person's email as the FROM field will cause DMARC to fail. You can read up about that here
Also I don't understand why you are using the person's email address and password to connect to gmail with. You should use your own account if you're sending mail.

Could not send mail from godaddy mail servier in ASP.NET

I am trying to send mail using GoDaddy mail server with SMTPClient in ASP.NET and my code is below , I have tried all the ports in GoDaddy but i couldn't send a mail
My code:
try
{
//Mail Message
MailMessage mM = new MailMessage();
//Mail Address
mM.From = new MailAddress("xxx#sender.com");
//receiver email id
mM.To.Add("xxx#receiver.com");
//subject of the email
mM.Subject = "your subject line will go here";
mM.Body = "Body of the email";
mM.IsBodyHtml = true;
//SMTP client
SmtpClient sC = new SmtpClient();
//credentials to login in to hotmail account
sC.Credentials = new NetworkCredential(username, password);
//port number for Hot mail
sC.Port = 25;
sC.Host = "smtpout.asia.secureserver.net";
sC.UseDefaultCredentials = false;
//enabled SSL
sC.EnableSsl = false;
sC.DeliveryMethod = SmtpDeliveryMethod.Network;
sC.Timeout = 40000;
//Send an email
sC.Send(mM);
}
catch (Exception ex)
{
var temp = ex.Message;
}
I have also used port no 465 with enablessl = true but no success
I was struggling with this too and found a solution.
The problem is that GoDaddy uses Implicit SSL (SMTPS) and this is NOT supported with System.Net.Mail.
It should be possible to use a GoDady Relay account, but then you can only send 250 emails per day AND the email sent will be SPAM unvisible at receiver side!
Then I found an open source library: http://sourceforge.net/projects/netimplicitssl/
You can get this package via NuGet in Visual Studio.
Search for: Aegis Implicit Mail.
I can tell you that this works perfectly !
private void _SendEmail()
{
try
{
var mail = "YourEmail#YourGoDaddyWebsite.com";
var host = "smtpout.europe.secureserver.net";
var user = "YourEmail#YourGoDaddyWebsite.com";
var pass = "YourGoDaddyPassword!";
//Generate Message
var message = new MimeMailMessage();
message.From = new MimeMailAddress(mail);
message.To.Add("receiver#website.com");
message.Subject = "Subject Text...";
message.Body = "Body Text...";
//Create Smtp Client
var mailer = new MimeMailer(host, 465);
mailer.User = user;
mailer.Password = pass;
mailer.SslType = SslMode.Ssl;
mailer.AuthenticationMode = AuthenticationType.Base64;
//Set a delegate function for call back
mailer.SendCompleted += compEvent;
mailer.SendMailAsync(message);
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
private void compEvent(object sender, AsyncCompletedEventArgs e)
{
if (e.UserState != null)
Console.Out.WriteLine(e.UserState.ToString());
Console.Out.WriteLine("is it canceled? " + e.Cancelled);
if (e.Error != null)
Console.Out.WriteLine("Error : " + e.Error.Message);
}
you should note you cannot sent non-html, or plain text emails. The message.IsBodyHtml member does not seem to work currently.

Catch exception in contact form

I'm going to create form contact in asp.net mvc 4. I have yet form in html and code in controller. And his looks like:
[HttpPost]
public ActionResult Kontakt(KontaktModel k)
{
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress(k.Mail.ToString());
StringBuilder sb = new StringBuilder();
msg.To.Add("myemail#gmail.com");
msg.Subject = k.Temat.ToString();
msg.IsBodyHtml = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
sb.Append("Nick / Imię i nazwisko: " + k.Name);
sb.Append(Environment.NewLine);
sb.Append("Typ problemu: " + k.TypProblemu);
sb.Append(Environment.NewLine);
sb.Append("Treść:");
sb.Append(Environment.NewLine);
sb.Append(k.Tresc);
msg.Body = sb.ToString();
smtp.Send(msg);
msg.Dispose();
return View("SUCCESS");
}
catch(Exception)
{
return View("Error");
}
}
return View();
}
}
But when I clicked to button app return Error.cshtml. I have a question, how I can know how exception catched? I don't know why it does not work. Any ideas?
The answer should be to get the Exception Message and put inside a ViewBag.Message and show it in the Error.cshtml view.
Error:
#ViewBag.Message
But is good to know little more about Exception and Exception Handling. If you only declare a try catch and a exception happen it will go inside the catch is the same if you do try catch(Exception) if you want to know more detail about the exception is happening you can declare a variable, example :
try{
///code
}catch(Exception e){}
and then you can watch inside the variable for more detail.
The good practice is to know what type of exception you can receive and handle, here is a link that have a good explanation Exception and Exception Handling
Example:
try
{
//code
}
catch(Exception c)
{
ViewBag.Message = c.Message
return View("ERROR");
}

Unable to send mail if one mail not present with ASP

I've written code for sending a newsletter, all is working fine, but there is a problem if one of the email addresses in the list, doesn't exit or the domain does not exist.
In this case the script stops immediately and the sending of the mail list is not finished.
Here is the part of the code I want to modify.
public static void SendMessage(String sender, String recipient, String message, String object)
{
try
{
MailMessage mail = new MailMessage(sender, recipient);
mail.Subject = object;
mail.IsBodyHtml = true;
mail.Body = message;
SmtpClient smtp = new SmtpClient();
smtp.Host = "my.smtp.com";
smtp.Send(mail);
}
catch (Exception e)
{ throw new Exception("AdminEmail - SendMessage >> recipient: " + recipient + " - generic error: " + e.Message); }
}
Hope somone can help me, thank you very much!
Welcome to SO.
From what I can infer from your description your are not handling the exception that is thrown by SendMessage.
Handle the exception in the caller method. Or do a dirty fix as shown below...
This is not a real fix. But will help you understand the issue...You have to determine in your calling method what to do if SendMessage throws an exception.
public static void SendMessage(String sender, String recipient, String message, String object)
{
try
{
MailMessage mail = new MailMessage(sender, recipient);
mail.Subject = object;
mail.IsBodyHtml = true;
mail.Body = message;
SmtpClient smtp = new SmtpClient();
smtp.Host = "my.smtp.com";
smtp.Send(mail);
}
catch (Exception e)
{
//Just log error and continue to process
}
}

ASP.NET Contact Form - output to email and access database

I am new to ASP.NET, and I am trying to create a contact form which sends an email at submission as well storing the data in a database.
I have read numerous tutorials, and I am pretty comfortable with a basic contact form to email setup - but I am having trouble with the database part of it.
Please let me know if you have ever done this, or if you could provide any information that would assist me with this task.
I am running ASP.NET 2.0
Thanks in advance.
I'm very new to both C# and ASP.NET (first year IT student). Up until a month ago, I'd never even viewed C# code, much less programmed anything in C#. I, too, have been combing the internet for a solution to this problem. After a week of tinkering with some code, I finally figured it out. The below code will allow you to create an ASP.NET "Contact Us" email form, and will send the information in the form to a SQL Server database. I hope this helps someone to avoid the same aggravation I went through! (If anyone knows a way to program this more efficiently, I'd love to hear your thoughts.)
HERE IS THE CODE FOR THE ASPX.CS FILE ATTACHED TO THE FORM:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Contact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Code for the Reset event (will reset form data):
protected void Reset(object s, EventArgs e)
{
fname.Text = "";
lname.Text = "";
email.Text = "";
phone.Text = "";
comments.Text = "";
}
//Code for the SendMail Event; will send email and write info in email into database:
protected void SendMail(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(email.Text);
mail.To.Add("EMAIL ADDRESS WHERE YOU'D LIKE THE MESSAGE SENT");
mail.Subject = "Contact Us";
mail.IsBodyHtml = true;
mail.Body += "First Name: " + fname.Text + "<br />";
mail.Body += "Last Name: " + lname.Text + "<br />";
mail.Body += "Comments: " + comments.Text + "<br />";
mail.Body += "Phone Number: " + phone.Text + "<br />";
SmtpClient smtp = new SmtpClient();
smtp.Host = "NAME OF SMTP RELAY SERVER";
smtp.Send(mail);
}
protected void insertInfo(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection (ConfigurationManager.ConnectionStrings["WEB.CONFIG CONNECTION STRING NAME"].ToString());
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO TABLE NAME (fname, lname, email, phone, comment)
VALUES (#fname, #lname, #email, #phone, #comments)";
cmd.Connection = myConnection;
cmd.Parameters.Add("#fname", fname.Text);
cmd.Parameters.Add("#lname", lname.Text);
cmd.Parameters.Add("#email", email.Text);
cmd.Parameters.Add("#phone", phone.Text);
cmd.Parameters.Add("#comments", comments.Text);
myConnection.Open();
cmd.ExecuteNonQuery();
myConnection.Close();
}
}

Resources