How to send a email from C#.net? [duplicate] - asp.net

This question already has answers here:
Sending email in .NET through Gmail
(26 answers)
Closed 9 years ago.
I am working on framework 2.I want to send email through my portal.I visited many site.From that I able to understand this much.Here is my code.I have created page design.What is smtpserver.This code giving me error.
System.Web.HttpException: The server rejected the sender address
MailMessage Msg = new MailMessage();
// Sender e-mail address.
Msg.From = txtFrom.Text;
// Recipient e-mail address.
Msg.To = txtTo.Text;
Msg.Subject = txtSubject.Text;
Msg.Body = txtBody.Text;
// your remote SMTP server IP.
SmtpMail.SmtpServer = "smtp.gmail.com";
SmtpMail.Send(Msg);
Msg = null;

if you want to send mail using gmail account than use this code
sing System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from_add#gmail.com", "name");
var toAddress = new MailAddress("to_add#example.com", "name");
const string fromPassword = "password";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Full soruce : How to Send Mails from your GMAIL Account through VB.NET or C#. Windows Programming, with a Bit of Customization

try this bellow code
Using System.Net.Mail;
public void SendEmail(string from, string to, string bcc, string cc, string subject,
string body)
{
try
{
MailMessage NewEmail = new MailMessage();
NewEmail.From = new MailAddress(from);
NewEmail.To.Add(new MailAddress(to));
if (!String.IsNullOrEmpty(bcc))
{
NewEmail.Bcc.Add(new MailAddress(bcc));
}
if (!String.IsNullOrEmpty(cc))
{
NewEmail.CC.Add(new MailAddress(cc));
}
NewEmail.Subject = subject;
NewEmail.Body = body;
NewEmail.IsBodyHtml = true;
SmtpClient mSmtpClient = new SmtpClient();
// Send the mail message
mSmtpClient.Send(NewEmail);
this.Label1.Text = "Email sent successful.";
}
catch
{
this.Label1.Text = "Email sent failed";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string from = "sender address";// like username#server.com
string to = TextBox1.Text; //Recipient address.
string bcc = "";
string cc = "";
string subject = "text";
string body = "text";
SendEmail(from, to, bcc, cc, subject, body);
}
Web.Config:
<system.net>
<mailSettings>
<smtp>
<network host="your stmp server" port="25" userName="your from email" password="your password"/>
</smtp>
</mailSettings>
</system.net>

Pass value as like below in sendMail method
sMailFrom=your Mail Id
sMailTo=To Mail Id
sSubj=Subject of Mail
sContent= Content of ur mail
bHTMLFormat=true
public static string sendMail(string sMailFrom, string sMailTo,
string sSubj, string sContent, bool bHTMLFormat)
{
try
{
System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage();
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
//System.Web.Mail.MailMessage mmsg = new MailMessage();
string smtpServer = ConfigurationSettings.AppSettings.Get("smtphost").ToString();
mmsg.From = new System.Net.Mail.MailAddress(sMailFrom);
mmsg.To.Add(sMailTo);
mmsg.Subject = sSubj;
mmsg.Body = sContent;
//mmsg.BodyFormat = (bHTMLFormat ? MailFormat.Html : MailFormat.Text);
mmsg.IsBodyHtml = bHTMLFormat;
smtpClient.Host = smtpServer;
if (ConfigurationSettings.AppSettings.Get("smtpport").ToString() != "")
smtpClient.Port = Convert.ToInt32(ConfigurationSettings.AppSettings.Get("smtpport").ToString());
smtpClient.UseDefaultCredentials = false;
System.Net.NetworkCredential mailCredential = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings.Get("EmailID").ToString(), ConfigurationSettings.AppSettings.Get("Password").ToString());
smtpClient.Credentials = mailCredential;
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Send(mmsg);
return "";
}
catch (Exception err)
{
return err.Message.ToString();
}
}

Related

ASP.NET MVC smtp error sending mail problem

I have already edited the webconfig file but I've got SmtpException "error sending mail". My domain port is 25. I've double checked. Here is my code. What's problem? Thank you.
public void SendEmail(string toAddress, string fromAddress,string subject, string message)
{
try
{
using (var mail = new MailMessage())
{
mail.From = new MailAddress(fromAddress);
mail.To.Add(new MailAddress(toAddress));
mail.Subject = subject;
mail.Body = message;
mail.IsBodyHtml = true;
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Host = "webmail.domain.com";
smtpClient.Port = 25;
smtpClient.Credentials = new NetworkCredential("blabla#domain.com", "pass");
smtpClient.Send(mail);
}
}
mail.Dispose();
}
}

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;
}
}

Asp.net 4.0 Sending Emails

I have aspx page where i have the email field like this
<input class="span12" type="text" placeholder="EMAIL" id="Email" name="Email" runat="server" />
In my Csharp file i have code and using Request["Email"] to get the address when visitor enter the email address which can be any so i want to email them as well my code is like Below, But it does not work, I am using .net 4.0, where i can change then that dynamic email whatever it would be i could get it and send email.
private void SendEmail(int RefNum)
{
var customerEmail = Request["Email"]; //getting value from aspx page.
MailMessage ObjEmail = new MailMessage();
ObjEmail.SendFrom = "carlaza#hotmail.ca";
ObjEmail.SendTo = "zjaffary#hotmail.com";
ObjEmail.SendCC = "jaffary_zafar#hotmail.com";
ObjEmail.SendBCC = customerEmail ;
ObjEmail.Subject = "test Subject ";
//Development
//SmtpMail.SmtpServer = "tormail.corp.kkt.ca";
//Production At Bell
SmtpMail.SmtpServer = "tormail.corp.kkt.ca";
ObjEmail.BodyFormat = MailFormat.Html;
string strBody1 = "Test message " ;
ObjEmail.Priority = MailPriority.High;
try {
SmtpMail.Send(ObjEmail);
lblResponse.Text = "Thank you for sending the form !";
Response.AddHeader("Refresh", "2;URL=index.aspx");
}
catch (Exception exc){
Response.Write("Send failure: " + exc.ToString());
}
}
You should use authetication information from web mail server. (user name and password) If not, that is not actual e-mail.
You can see the code and can work
SmtpClient SmtpServer = new SmtpClient("smtp.live.com");
var mail = new MailMessage();
mail.From = new MailAddress("youremail#hotmail.com");
mail.To.Add("to#gmail.com");
mail.Subject = "Test Mail - 1";
mail.IsBodyHtml = true;
string htmlBody;
htmlBody = "Write some HTML code here";
mail.Body = htmlBody;
SmtpServer.Port = 587;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("youremail#hotmail.com", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
Please see the topic. I think it is helpfull for you.
How to add smtp hotmail account to send mail
How to add smtp hotmail account to send mail
try this
protected void sendEmail(string subject, string ToEmail, string msg)
{
String body = msg;
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("your_email_id");
smtpClient.Host = "smtp.gmail.com";//host
smtpClient.Port = 587;//port no. default 25
smtpClient.UseDefaultCredentials = false;
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential("your_email_id", "password");
message.From = fromAddress;
message.To.Add(ToEmail);//if more than comma seprated
message.Subject = subject;
message.Priority = MailPriority.High;
message.Body = body;
message.IsBodyHtml = true;
smtpClient.Send(message);
}

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);

How can i send a comment in email?

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.

Resources