My Code on Button_Click is
Massage = "Name :" + txtname.Text + "\nEmail :" + txtemail.Text + "\nPhone :" + TextBox3.Text + "\nMassage :" + TextBox4.Text;
eMail.Mail(null, "contact us", "vermarajneesh344#gmail.com", null, null, "contact us", Massage, null, null);
and the code behind is
public class eMail
{
public static bool Mail(string FromEmailAddress, string FromDisplayName, string ToAddress, string ToAddressCC, string ToAddressBCC, string Subject, string bodytxt, string HostName, string AttachFileName)
{
bool functionReturnValue = false;
//*******example
//// System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
//// System.Net.Mail.SmtpClient is the alternate class for this in 2.0
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
if (string.IsNullOrEmpty(FromEmailAddress))
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["FromEmailAddress"].ToString()))
FromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
MailAddress fromAddress = new MailAddress(FromEmailAddress, FromDisplayName);
// // You can specify the host name or ipaddress of your server
//// Default in IIS will be localhost
if (string.IsNullOrEmpty(HostName))
{
if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["HostName"].ToString()))
HostName = "smtp.gmail.com"; //"mail.osmor.org";
else
HostName = ConfigurationManager.AppSettings["HostName"].ToString();
}
smtpClient.Host = HostName;
////Default port will be 25
if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["smtpClientPort"].ToString()))
smtpClient.Port = 465;
else
smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["smtpClientPort"].ToString());
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ESSL"].ToString()))
{
if (ConfigurationManager.AppSettings["ESSL"].ToString() == "true")
smtpClient.EnableSsl = true;
else
smtpClient.EnableSsl = false;
}
////From address will be given as a MailAddress Object
message.From = fromAddress;
//// To address collection of MailAddress
if (string.IsNullOrEmpty(ToAddress))
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ToAddress"].ToString()))
ToAddress = ConfigurationManager.AppSettings["ToAddress"].ToString();
string[] tmp = null;
int i = 0;
tmp = Mainclass.SplitByString(ToAddress, ",");
for (i = 0; i <= tmp.Length - 1; i++)
{
message.To.Add(tmp[i].ToString());
//"firsttime#sector-17.com")
message.Subject = Subject;
//"Feedback"
}
//// CC and BCC optional
//// MailAddressCollection class is used to send the email to various users
// // You can specify Address as new MailAddress("admin1#yoursite.com")
if (string.IsNullOrEmpty(ToAddressCC))
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ToCC"].ToString()))
ToAddressCC = ConfigurationManager.AppSettings["ToCC"].ToString();
if (!string.IsNullOrEmpty(ToAddressCC))
{
tmp = Mainclass.SplitByString(ToAddressCC, ",");
for (i = 0; i <= tmp.Length - 1; i++)
{
message.CC.Add(tmp[i].ToString());
//
}
}
//ToAddressBCC = "amangargptl#gmail.com";
// // You can specify Address directly as string
if (!string.IsNullOrEmpty(ToAddressBCC))
{
tmp = Mainclass.SplitByString(ToAddressBCC, ",");
for (i = 0; i <= tmp.Length - 1; i++)
{
message.Bcc.Add(new MailAddress(tmp[i].ToString()));
}
}
// //message.Bcc.Add(new MailAddress("admin4#yoursite.com"));
////Body can be Html or text format
// //Specify true if it is html message
message.IsBodyHtml = true;
String UserName, Password;
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["UserName"].ToString()))
UserName = ConfigurationManager.AppSettings["UserName"].ToString();
else
UserName = "UserName";
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Password"].ToString()))
Password = ConfigurationManager.AppSettings["Password"].ToString();
else
Password = "Password";
smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
//// Message body content
message.Body = bodytxt;
if (!string.IsNullOrEmpty(AttachFileName))
message.Attachments.Add(new Attachment(HttpContext.Current.Server.MapPath("~/" + AttachFileName)));
// // Send SMTP mail
smtpClient.Send(message);
// lblStatus.Text = "Email successfully sent.";
functionReturnValue = true;
}
catch (Exception ex)
{
bodytxt = "Send Email Failed.<br>" + ex.Message;
//;
//Mainclass.WriteErorrFile(ex.Message, "Macadamia", "Mail");
//c.msg(ex.Message, response)
functionReturnValue = false;
// throw;
}
return functionReturnValue;
}
and code on web.config is
<appSettings>
<add key="bh" value="Travel Holidays"/>
<add key="FromEmailAddress" value="info#Travelholidays.com"/>
<add key="ToAddress" value=""/>
<add key="ToCC" value=""/>
<add key="HostName" value="smtp.gmail.com"/>
<add key="UserName" value="info#Travelholidays.com"/>
<add key="Password" value="password"/>
<add key="smtpClientPort" value="587"/>
<add key="ESSL" value="true"/>
</appSettings>
Thanks..
help would be greatly appreciated
Use these setting in your web.config
<system.net>
<mailSettings>
<smtp from="sender#gmail.com ">
<network host="smtp.gmail.com" defaultCredentials="false"
port="587" enableSsl="true" userName="Sender#gmail.com" password="*******" />
</smtp>
</mailSettings>
</system.net>
In your .aspx.cs use
StringBuilder emailMessage = new StringBuilder();
emailMessage.Append("Email body here");
MailMessage email = new MailMessage();
email.To.Add(new MailAddress("ReceiverEmailAddress"));
email.Subject = "Mail Subject";
email.From = new MailAddress("sender#gmail.com");
email.Body = emailMessage.ToString();
email.IsBodyHtml = true;
//Send Email;
SmtpClient client = new SmtpClient();
client.Send(email);
That's it. Hope it works
Related
private string sendEmail(string emailId,string userID)
{
try
{
userID = Encrypt(userID);
MailMessage mail = new MailMessage();
mail.To.Add(emailId);
mail.From = new MailAddress("");
//mail.Subject = "Your password for account " + emailId;
string userMessage = "http://localhost/LoginWithSession/ResetPassword" + userID;
userMessage = userMessage + "<br/><b>User Id:</b> " + emailId;
//userMessage = userMessage + "<br/><b>Passsword: </b>" + password;
string Body = "<br/><br/>Please click on link to reset your password:<br/></br> " + userMessage + "<br/><br/>Thanks";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //SMTP Server Address of gmail
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("harianasaif#gmail.com", "test");
// Smtp Email ID and Password For authentication
smtp.EnableSsl = true;
smtp.Send(mail);
return userMessage;
}
catch (Exception ex)
{
return "Error............" + ex;
}
}
**1. This is my code to send email
Problem is I cannot open Reset Page when clicked on URL
I have created the virtual directory as well**
Please check this
Here you need to add <a> tag for called the URL.
//Create one function for getting URL run time like localhost or any domain name
public string GetUrl()
{
var request = Request;
return string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, (new System.Web.Mvc.UrlHelper(request.RequestContext)).Content("~"));
}
private string sendEmail(string emailId,string userID)
{
try
{
userID = Encrypt(userID);
MailMessage mail = new MailMessage();
mail.To.Add(emailId);
mail.From = new MailAddress("");
//mail.Subject = "Your password for account " + emailId;
string userMessage = string.Concat("<a href='",GetUrl(), "LoginWithSession/ResetPassword/", userID,"'>");
userMessage = userMessage + "<br/><b>User Id:</b> " + emailId+"</a>";
//userMessage = userMessage + "<br/><b>Passsword: </b>" + password;
string Body = "<br/><br/>Please click on link to reset your password:<br/></br> " + userMessage + "<br/><br/>Thanks";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //SMTP Server Address of gmail
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential();
// Smtp Email ID and Password For authentication
smtp.EnableSsl = true;
smtp.Send(mail);
return userMessage;
}
catch (Exception ex)
{
return "Error............" + ex;
}
}
i am trying to send email from my web app. i am using smtp gmail for the same. but for some reasons i am not able to send a mail.. i have tried port numbers like 25,465,587 but none of these are working....
public static void SendMail(string host, string senderName, string frmAddress, string toAddress, int port, string subject, string messageText)
{
String smtpHost, port1;
smtpHost = ConfigurationManager.AppSettings["smtphost"].ToString();
port1 = ConfigurationManager.AppSettings["smtpport"].ToString();
SmtpClient mailClient = new SmtpClient(smtpHost, Convert.ToInt16(port1));
mailClient.EnableSsl = true;
NetworkCredential cred = new NetworkCredential();
cred.UserName = ConfigurationManager.AppSettings["username"].ToString();
cred.Password = ConfigurationManager.AppSettings["password"].ToString();
mailClient.Credentials = cred;
mailClient.UseDefaultCredentials = false;
//mailClient.Credentials = cred;
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
try
{
MailAddress fromAddress = new MailAddress(frmAddress, senderName);
message.From = fromAddress;
message.To.Add(toAddress);
message.Subject = subject;
message.IsBodyHtml = false;
message.Body = messageText;
mailClient.Send(message);
//Response.Write("<script language='javascript' type='text/javascript'>window.alert('Email Successfully Sent.');</script>");
}
catch
{
//Response.Write("<script language='javascript' type='text/javascript'>window.alert('Send Email Failed '" + ex.Message + ");</script>");
}
}
calling this method:
protected void btnMail_Click1(object sender, EventArgs e)
{
string from = txtEmail.Text;
string to = "my gmail id";
string message = taMessage.InnerText;
Global.SendMail(ConfigurationManager.AppSettings["smtphost"].ToString(), txtName.Text, from, to, Convert.ToInt32(ConfigurationManager.AppSettings["smtpport"]), "Enquiry", taMessage.InnerText);
}
web.config settings :
<appSettings>
<add key="smtphost" value="smtp.gmail.com"/>
<!--<add key="smtphost" value="103.231.41.229"/>-->
<add key="smtpport" value="587"/>
<!--<add key="port" value="25"/>-->
<add key="username" value="my gmail id/>
<add key="password" value="my password"/>
<add key="From" value="my gmail id"/>
</appSettings>
Exception : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication
Its a security issue, Gmail by default prevents access for your mail account from custom applications. You can set it up to accept the login from your application.
After Logging in to your mail ,
https://www.google.com/settings/security/lesssecureapps
Update:
msg.IsBodyHtml = true;
Try this:-
protected void Button1_Click(object sender, EventArgs e)
{
// body
//subject
//reciever id
sendmail(recieverID, subject, body);
}
method for sending mail
protected void sendmail(string reciever, string subject, string body)
{
string senderID = "sender email id";
string pwd = "password ";
string result = "Message Sent Successfully";
try
{
SmtpClient smtpClient = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential(senderID, pwd),
Timeout = 30000
};
MailMessage msg = new MailMessage(senderID, reciever, subject, body);
msg.IsBodyHtml = true;
smtpClient.Send(msg);
}
catch
{
result = "Error Sending Mail";
}
Response.Write(result );
}
OR
U can also go through this link
public void SendEmailWithAttachment(string pFrom, string pTo, string pSubject, string pBody, string pServer, string strAttachmentPDFFileNames)
{
try
{
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
string UserName = ConfigurationManager.AppSettings["SMTPUserName"];
string Password = ConfigurationManager.AppSettings["SMTPPassword"];
if (pTo.Contains(","))
{
string[] ToAdd = pTo.Split(new Char[] { ',' });
for (int i = 0; i < ToAdd.Length; i++)
{
Message.To.Add(ToAdd[i]);
}
}
else
{
Message.To.Add(pTo);
}
//System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(pTo);
//Message.To.Add(toAddress);
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress(pFrom);
Message.From = fromAddress;
Message.Subject = pSubject;
Message.Body = pBody;
Message.IsBodyHtml = true;
// Stream streamPDFImages = new MemoryStream(bytPDFImageFile);
//System.Net.Mail.SmtpClient
var smtpClient = new System.Net.Mail.SmtpClient();
{
Message.Attachments.Add(new System.Net.Mail.Attachment(strAttachmentPDFFileNames));
smtpClient.EnableSsl = true;
smtpClient.Host = pServer;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
smtpClient.Port = 465;
smtpClient.Send(Message);
}
}
catch (Exception Exc)
{
Exception ex = new Exception("Unable to send email . Please Contact administrator", Exc);
throw ex;
}
}
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("yourMail", "yourPassword");
smtp.EnableSsl = true;
MailMessage msg = new MailMessage(sendFrom, "yourMail");
msg.ReplyToList.Add(sendFrom);
msg.Subject = subject;
msg.Body = bodyTxt;
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(#"C:\Projects\EverydayProject\test.txt");
msg.Attachments.Add(attachment);
smtp.Send(msg);
Here is working code to send an email to gmail smtp. From what I see you don't set UseDefaultCredentials = false and you are using wrong port. Also you MUST NOT override exceptions like this., throw the initial exception. Also for this to work you need to turn off security setting in your Gmail account. You can google it.
I have contact page on my website and I want users to enter Their name and email id (no password) and send email on button click.
I did Google and all solutions i am getting requires user password,
public static void SendMessage(string subject, string messageBody, string toAddress, string ccAddress, string fromAddress)
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
// Set the sender's address
message.From = new MailAddress(fromAddress);
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
// Allow multiple "Cc" addresses to be separated by a semi-colon
if (ccAddress.Trim().Length > 0)
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
// Set the subject and message body text
message.Subject = subject;
message.Body = messageBody;
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtpHost";
smtp.Port =portno;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("fromEmail", "fromPassword");
smtp.Timeout = 20000;
}
// Send the e-mail message
smtp.Send(message);
}
But I don't want to force users to enter password. Is there any other solution using SMTP?
The error I am getting is A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I have this function in my utility class , and it works like a charm.
public static bool SendMail(string Email, string MailSubject, string MailBody)
{
bool isSent = false, isMailVIASSL = Convert.ToBoolean(ConfigurationManager.AppSettings["MailServerUseSsl"]);
string mailHost = ConfigurationManager.AppSettings["MailServerAddress"].ToString(),
senderAddress = ConfigurationManager.AppSettings["MailServerSenderUserName"].ToString(),
senderPassword = ConfigurationManager.AppSettings["MailServerSenderPassword"].ToString();
int serverPort = Convert.ToInt32(ConfigurationManager.AppSettings["MailServerPort"]);
MailMessage msgEmail = new MailMessage(new MailAddress(senderAddress), new MailAddress(Email));
using (msgEmail)
{
msgEmail.IsBodyHtml = true;
msgEmail.BodyEncoding = System.Text.Encoding.UTF8;
msgEmail.Subject = MailSubject;
msgEmail.Body = MailBody;
using (SmtpClient smtp = new SmtpClient(mailHost))
{
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = isMailVIASSL;
smtp.Credentials = new NetworkCredential(senderAddress, senderPassword);
smtp.Port = serverPort;
try
{
smtp.Send(msgEmail);
isSent = true;
}
catch (Exception ex)
{
throw ex;
}
}
}
return isSent;
}
<!-- Mail Server Settings -->
<add key="MailServerAddress" value="smtp.gmail.com" />
<add key="MailServerPort" value="25" />
<add key="MailServerSenderUserName" value="username#gmail.com" />
<add key="MailServerSenderPassword" value="password" />
<add key="MailServerUseSsl" value="True" />
I am trying to send a basic email to a folderbut howerver, even though I do receive the email, the body is missing completely.
private void MailReport()
{
string to = "arianul#gmail.com";
string From = "ArianG#lr.co.za";
string subject = "Report";
**string Body = "Dear sir ,<br> Plz Check d Attachment <br><br>";**
bool send = sendMail(to, From, subject, Body);
if (send == true)
{
string CloseWindow = "alert('Mail Sent Successfully!');";
ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
}
else
{
string CloseWindow = "alert('Problem in Sending mail...try later!');";
ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
}
}
public bool sendMail(string to, string from, string subject, string body)
{
bool k = false;
try
{
MailMessage msg = new MailMessage(from, to);
msg.Subject = subject;
AlternateView view;
SmtpClient client;
StringBuilder msgText = new StringBuilder();
view = AlternateView.CreateAlternateViewFromString(msgText.ToString(), null, "text/html");
msg.AlternateViews.Add(view);
msgText.Append("<body><br></body></html> <br><br><br> " + body);
client = new SmtpClient();
client.Host = "staging.itmaniax.co.za";
client.Send(msg);
k = true;
}
catch (Exception exe)
{
Console.WriteLine(exe.ToString());
}
return k;
}
<system.net>
<mailSettings >
<smtp deliveryMethod="specifiedPickupDirectory" from="ArianG#lr.co.za">
<network host="staging.itmaniax.co.za"/>
<specifiedPickupDirectory pickupDirectoryLocation="C:\testdump\emaildump\"/>
</smtp>
</mailSettings>
I have the feeling the problem lies with the body and the html as it is done with visual studio-2008.
Any advice perhaps?
You can try something like below.
protected void SendMail()
{
// Gmail Address from where you send the mail
var fromAddress = "Gmail#gmail.com";
// any address where the email will be sending
var toAddress = YourEmail.Text.ToString();
//Password of your gmail address
const string fromPassword = "Password";
// Passing the values and make a email formate to display
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";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//here on button click what will done
SendMail();
DisplayMessage.Text = "Your Comments after sending the mail";
DisplayMessage.Visible = true;
YourSubject.Text = "";
YourEmail.Text = "";
YourName.Text = "";
Comments.Text = "";
}
catch (Exception) { }
}
For more information check Send Mail / Contact Form using ASP.NET and C#
I hope this will help to you.
it seems that you are missing the:
MailMessage msg = new MailMessage(from, to);
msg.Subject = subject;
msg.Body = body; <--- try adding this and see what happens.
msg.Body property is empty in your example, I guess that's why it doesn't send the body text.