How can i send a comment in email? - asp.net

I have some text boxes like name,email address,phone no. and comment on my page.
I have to send the values to my email address..
How should I do this??
I am doing:
protected void btnSubmit_Click(object sender, EventArgs e)
{
SmtpClient client = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);
SmtpClient.Host = "localhost";
SmtpClient.Port = 25;
message.From = fromAddress;
message.To.Add("xyz#gmail.com");
message.Subject = "Feedback";
message.IsBodyHtml = false;
message.Body = txtComment.Text;
SmtpClient.Send(message);
Response.Write("Email successfully sent.");
}
catch (Exception ex)
{
Response.Write("Send Email Failed." + ex.Message);
}
}
and I am getting the following error:
An object reference is required for the nonstatic field, method, or property 'System.Net.Mail.SmtpClient.Send(System.Net.Mail.MailMessage)'

SmtpClient.Host = "localhost";
SmtpClient.Port = 25;
~~~~~~~~~~~~~~~~~~~~
SmtpClient.Send(message);
These lines are attempting to use members of the class SmtpClient. However, as these members are not defined as static, you need to refer to your instance of that class, which you have called client.
Try
client.Host = "localhost";
client.Port = 25;
~~~~~~~~~~~~~~~~~~~~
client.Send(message);
Also, have a read of this article on the differences between class and instance members.
Finally, as SmtpClient implements IDisposable, I would change your code to wrap it in a using block, as this will ensure you are correctly cleaning up your SMTP session after you are finished with it.
using (SmtpClient client = new SmtpClient())
{
// YOUR CODE
}

public static string sendMail(string to, string title, string subject, string body)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);
if (to == "")
to = fromAddress.Address;
MailAddressCollection m = new MailAddressCollection();
m.Add(to);
mail.Subject = subject;
mail.From = fromAddress;
mail.Body = body;
mail.IsBodyHtml = true;
mail.ReplyTo = fromAddress;
mail.To.Add(m[0]);
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential(fromAddress.Address, "XXXX");//"XXXX" is the password of the sender.
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(mail);
return "done";
}
catch (Exception ex)
{
return ex.Message;
}
}

i had done this:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
MailMessage mailmsg = new MailMessage();
string name = txtName.Text.ToString();
string contact = txtPhoneNo.Text.ToString();
string comment = txtComment.Text.ToString();
string checkIn = txtCheckIn.Text.ToString();
string from = txtEmail.Text.ToString();
mailmsg.To.Add("recipientemailid#gmail.com");
mailmsg.From = new MailAddress(from.Trim());
mailmsg.Subject = "Test message";
mailmsg.Body = "This Query is submitted by user " + name.Trim() + ", "+ contact.Trim() + ", " + comment.Trim() + ", " + checkIn.Trim();
mailmsg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
NetworkCredential credentials = new NetworkCredential("recipientemailid#Gmail.com", "password");
client.Credentials = credentials;
try
{
//try to send the mail message
client.Send(mailmsg);
Response.Write("sent!");
}
catch
{
//some feedback if it does not work
Response.Write("failed!");
}
}

Try
client.Host = "localhost";
client.Port = 465;
~~~~~~~~~~~~~~~~~~~~
client.Send(message);
Do not try to use or manage disposable emails with this because you will be clearly exposed to spam-trappers. Your code is open and very easy to identify who is using the code and from where.

Related

I want to send email through my ASP.Net website

the email code works on local host but when i upload the website on server it shows error
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
//Formatted
protected void btnSend_Click(object sender, EventArgs e)
{
var fromAddress = "djdanny1255#gmail.com";
string email = "djdanny1255#gmail.com";
var toAddress = email;
const string fromPassword = "********";
string subject = "Email=" + txtEmail.Text + " Phone=" + txtMobile.Text;
string body = txtMessage.InnerText;
try
{
using (MailMessage mm = new MailMessage(fromAddress, email))
{
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(fromAddress, fromPassword);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
}
catch (Exception ex)
{
Response.Write("Error" + ex.Message);
}
in first cas, i suggest you to change code at this code :
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(fromAddress);
mail.To.Add(toAddress);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress,fromPassword);
smtp.Send(mail);
}
}
and second after your Login in to your email, CLICK HERE .
This will see this page
i hope this help you ^^

I want to code to send mail and message in asp.net

This is my code:
string from = "rashmi#example.com";
string to = "rashmi#example.com";
string mailSubject = "mail demo";
string mailBody = "mail sent successfully";
MailMessage mess = new MailMessage(from, to, mailSubject, mailBody);
mess.IsBodyHtml = true;
SmtpClient emailClient = new SmtpClient("192.168.43.1", 25); //Server ip & port
emailClient.UseDefaultCredentials = false;
emailClient.Credentials = new System.Net.NetworkCredential("rashmi#example.com", "****password****");
try
{
emailClient.Send(mess);
Response.Write("message sent");
}
catch (Exception ex)
{
Response.Write("Exception caught in CreateTestMessage1(): {0}"+ ex.ToString());
}
but I get this error:
Exception caught in CreateTestMessage1(): {0}System.Net.Mail.SmtpException: Service not available, closing transmission channel. The server response was: Cannot connect to SMTP server 192.168.43.1 (192.168.43.1:25), connect error 10061
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message) at mail_demo_project.register_mail_demo.submit_Click(Object sender, EventArgs e) in e:\dot net\projects\mail demo project\mail demo project\register_mail_demo.aspx.cs:line 53
error occured...
Use this code to send email:
string From = "fromemailaddress#gmail.com";
MailAddress mailAddress = new MailAddress(From, "Contact Us");
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("toemailaddress#gmail.com");
mailMessage.From = mailAddress;
mailMessage.Subject = Txt_Subject.Text;
string mailBody = "User Email: " + Txt_msg.Text + "<br/> User Name: " + Txt_Name.Text + "<br/> Message: " + Txt_msg.Text ;
mailMessage.Body = mailBody;
mailMessage.Priority = MailPriority.Normal;
mailMessage.IsBodyHtml = true;
System.Net.NetworkCredential credential = new System.Net.NetworkCredential(From, "password");
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = false;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = credential;
smtpClient.Send(mailMessage);
and you have to make some security modification in your gmail account in security section :Allow less secure apps: YES

Getting Error- Invalid mail Attachment

I am trying to send email with excel file attachment. But getting invalid mail attachment error.
Please help me.
Here is my code-
Here is code for Email sending-
protected void btnSend_Click(object sender, EventArgs e)
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new MailAddress(txtFrom.Text);
msg.To.Add(txtTo.Text);
msg.Subject = txtSubject.Text;
if (FileUpload1.HasFile)
{
String FileName = FileUpload1.PostedFile.FileName;
MailAttachment mailAttachment = new MailAttachment(FileName, MailEncoding.Base64);
// msg.Attachments.Add(mailAttachment);
msg.Attachments.Add(mailAttachment);
}
using (SmtpClient client = new SmtpClient())
{
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(txtFrom.Text, txtPassword.Text);
client.Host = "smtp.gmail.com";
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(msg);
}
}
Right click on project name in solution explorer . Click on Add then Choose new folder name it MailDocuments. Use this code to Save it and Attach It.
if (FileUpload1.HasFile)
{
string fileName = FileUpload1.PostedFile.FileName;
string Path = Server.MapPath("~/MailDocuments/");
FileUpload1.PostedFile.SaveAs(Path + fileName);
MailAttachment ma = new MailAttachment(Server.MapPath("~/MailDocuments/" + fileName), MailEncoding.Base64);
msg.Attachment.Add(ma);
}
private bool SendEmail(string myIPAddress)
{
bool emailsent = true;
if (myemailaddress != "" && mypassword != "")
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(myemailaddress);
mail.CC.Add("whoever#yahoo.com");
mail.From = new MailAddress("do.not.reply#whatever.com", "do.not.reply#whatever.com", System.Text.Encoding.UTF8);
mail.Subject = "Type Subject Here";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "Your IP address has changed to " + myIPAddress;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("yourGmailEmail#gmail.com", "thepasswordforthataccount");
client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
try
{
client.Send(mail);
}
catch (Exception ex)
{
emailsent = false;
}
}
else
{
emailsent = false;
}
return emailsent;
}

how to send email through asp.net web api

i am making a windows phone app in which i want to give the forgot password functionality.
the app will send a email to stored email id of the user when he will press on forget password button.
As there is no smtp class available in windows phone , so i want to make a asp.net web api which will receive email id(and password) from the app and will send an email to that id.
I am new in web services and have 0 knowledge of this
please guide me how to achieve this task and if anyone can provide the code, there must be some web service available like this.
Here is an example of a function that sends an email you can use. Also, there are couple links below that can guide you in creating web service in ASP.NET
In reality, you don’t need to create a web service for this (although it’s recommended). You can create a quick and dirty web form where you pass parameters like this example.com/sendemail.aspx?account=jack.smith&id=223232343
private static void SendEmail(string from, string from_name, string to, string cc, string bcc, string subject, string body, bool isHtml)
{
SmtpClient mailClient = new SmtpClient(Config.SmptSettings.Server);
mailClient.Credentials = new NetworkCredential(Config.SmptSettings.UserName, Config.SmptSettings.Password);
mailClient.Port = Config.SmptSettings.Port;
MailMessage message = new MailMessage();
if (!string.IsNullOrEmpty(from_name))
{
message.From = new MailAddress(from, from_name);
}
else
{
message.From = new MailAddress(Formatter.UnFormatSqlInput(from));
}
message.To.Add(new MailAddress(to));
if (!string.IsNullOrEmpty(bcc, cc))
{
message.CC.Add(cc);
message.Bcc.Add(bcc);
}
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = isHtml;
mailClient.EnableSsl = Config.SmptSettings.SSL;
mailClient.Send(message);
}
## Call this function in your WebApi controller ##
private void sendEmailViaWebApi()
{
string subject = "Email Subject";
string body = "Email body";
string FromMail = "shahid#reckonbits.com.pk";
string emailTo = "reciever#reckonbits.com.pk";
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.reckonbits.com.pk");
mail.From = new MailAddress(FromMail);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("shahid#reckonbits.com.pk", "your password");
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
}
For those using .NET Core, note that there is currently no support for sending emails.
See the following issue for .NET Core via GitHub:
https://github.com/dotnet/corefx/issues/1006
A an alternative solution has been implemented - MailKit:
https://github.com/jstedfast/MailKit
string random;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string s1 = string.Empty;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select EmailId from tblEmail where EmailId='" + txtemail.Text + "'", con);
SqlDataReader dr =cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
s1 = dr.GetString(0);
}
}
dr.Close();
if (s1.Equals(txtemail.Text))
{
Session["Email"] = txtemail.Text;
try
{
Random rndm = new Random();
random = rndm.Next(99999).ToString();
MailMessage message = new MailMessage();
message.From = new MailAddress("yourid#gmail.com");
message.To.Add(new MailAddress(txtemail.Text));
message.Subject = " Hello... This is Your Serial No to change your password:";
message.Body = random.ToString();
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;//Gmail port number
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("yourid#gmail.com", "yourpassword");
client.Send(message);
SqlCommand cmd1 = new SqlCommand("insert into tblRandom values('" + txtemail.Text + "','" + random.ToString() + "')", con);
cmd1.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('Security Code Successfully Sent in Your Email Id')</script>");
Response.Redirect("~/anotherpage.aspx");
}
catch (Exception)
{
// Response.Write(ee.Message);
lblmsg.Text = "Please Enter Email-Id..";
lblmsg.Visible = true;
//MessageBox.Show("Please Enter Email-ID");
//Response.Write("<script>alert('Please Enter Email-ID')</script>");
}
}
else
{
lblmsg.Text = "Please Enter Correct Email-Id..";
lblmsg.Visible = true;
}
}

How to Send Mail in Asp.net in C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
No connection could be made because the target machine actively refused it?
I Face Critical Problem During Sending Mail in Asp.net please tell me Solution if Anyone know About this.
This Is My Code for Sending Mail
MailMessage mm = new MailMessage();
SmtpClient smtp = new SmtpClient();
mm.From = new MailAddress(txtfrom.Text);
mm.To.Add(new MailAddress(txtto.Text));
mm.Subject = txtsubject.Text;
mm.Body = txtmessage.Text;
mm.IsBodyHtml = true;
smtp.Host = "smtp.gmail.com"; //You can add this in the webconfig
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "mymail#gmail.com";
NetworkCred.Password = "my password";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587; //this is Gmail port for e-mail
smtp.Send(mm);//send an e-mail
The Problem is That when i Click on Send Button it Show following Error
"No connection could be made because the target machine actively
refused it 173.194.79.109:587"
Please tell me Solution ..
you need to set false the UseDefaultCredentials property.
smtp.UseDefaultCredentials = false;
That error message usually means a firewall is blocking your connection. Instead of using your machine name "173.194.79.109:587", try using "localhost".
protected void SendMail_Click(object sender, EventArgs e)
{
var fromAddress = new MailAddress(fromid.Text, fromname.Text);
var toAddress = new MailAddress(toid.Text, toname.Text);
string fromPassword = pswd.Text;
string subject = subjectbox.Text;
string body = bodybox.Text;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
IsBodyHtml = false
})
{
smtp.Send(message);
}
}
This is the function which i checked to send mail...and it's working properly.
`
private static bool testsendemail(MailMessage messageBody)
{
try
{
MailMessage message1 = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
MailAddress fromAddress = new MailAddress("FromMail#Test.com");
message1.From = fromAddress;
message1.To.Add("ToMail#Test1.com");
message1.Subject = "This is Test mail";
message1.IsBodyHtml = true;
message1.Body ="You can write your body here"+messageBody;
smtpClient.Host = "smtp.mail.yahoo.com"; // We use yahoo as our smtp client
smtpClient.Port = 587;
smtpClient.EnableSsl = false;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("SenderMail#yahoo.com", "YourPassword");
smtpClient.Send(message1);
}
catch
{
return false;
}
return true;
}`
Thank You.
This is how I use it.
SmtpClient gglClient = new SmtpClient("173.194.67.108", 587);
gglClient.UseDefaultCredentials = false;
gglClient.DeliveryMethod = SmtpDeliveryMethod.Network;
gglClient.Credentials = new NetworkCredential("username#gmail.com", "password");
gglClient.EnableSsl = true;
MailMessage msg = new MailMessage("", email);
msg.Subject = "";
msg.Body = #" ";
msg.IsBodyHtml = false;
msg.BodyEncoding = UTF8Encoding.UTF8;
gglClient.Timeout = 8000;
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors) { return true; };
gglClient.Send(msg);

Resources