Click here to Skip to main content
15,878,809 members
Please Sign up or sign in to vote.
3.88/5 (5 votes)
See more:
Hi,I want to do code for sending mail to the user in case of Forget Password.i want that when user request for his password his password automatically send to his email id taking data from database as in most of the sites its happened.But i am unable to send even a simple mail also.My code is:
C#
SmtpClient smtpclient = new SmtpClient();
MailMessage message = new MailMessage();
smtpclient.Host = "localhost";

try
{
    MailAddress SendFrom = new MailAddress(T1.Text);
    MailAddress SendTo = new MailAddress(T2.Text);
    MailMessage MyMessage = new MailMessage(SendFrom, SendTo);
    MyMessage.Subject = T3.Text;
    MyMessage.Body = T4.Text;
    T5.Text = "Message Sent";
catch (Exception ex)
{
    T5.Text = ex.ToString();
}

In my web.config,i am writing this to set smtp server:

XML
<system.net>
  <mailsettings>
    <smtp deliverymethod="Network">
      <network host="localhost" port="25" defaultcredentials="true" />
    </smtp>
  </mailsettings>
</system.net>



Its running successfully but its not sending mail to my mail id in real.whats wrong with this.what i have to do more.In my system IIS is not installed,does it create the problem?please suggest.
Posted
Updated 15-Aug-10 5:29am
v3
Comments
Kunal Chowdhury «IN» 15-Aug-10 11:29am    
Modified for proper code readability.

Simply use this method to send the mail. (yes you may need to setup your SMTP server so that it can send send mails from the localhost PC). Also, dont forget to use "System.web.mail" namespace for using this code. This will do the bit you need.

C#
protected void btnSendMail_Click(object sender, EventArgs e)
{
    MailMessage mailMessage = new MailMessage();
    mailMessage.From = "xyz@gmail.com";
    mailMessage.To = "abc@gmail.com";
    mailMessage.Subject = "test";
    mailMessage.BodyFormat = MailFormat.Text;
    mailMessage.Body = "this is a test mail...";
    mailMessage.Priority = MailPriority.High;
    SmtpMail.SmtpServer = "127.0.0.1";
    SmtpMail.Send(mailMessage);
    lblStatus.Text = "Your mail was sent";
}


Anurag
@Cheers@
 
Share this answer
 
v2
Comments
fwr 10-Aug-10 6:18am    
its not working sir,when i run the code it gives error regarding "Web.Dev.Webserver.exe" and shows message that unable to connect ASP.NET Development server.
fwr 10-Aug-10 6:41am    
Sorry, problem is getting in my project.none of my form is running.i am trying to solve it.thanks
fwr 11-Aug-10 5:24am    
Its giving connection error"The transport failed to connect to the server."
Mukund Kallapur 19-Sep-10 7:04am    
I tried the solution provided above...it does not give any error. but mail is also not sent
You have to set up localhost so that it is a valid mail server that is connected to the internet.
 
Share this answer
 
Comments
fwr 10-Aug-10 1:51am    
Thanks sir,one more thing is that in my system IIS is not installed.is it creating the problem?how can i set up my local host.
bithe 19-Sep-12 7:34am    
how to set up localhost ??
bithe 19-Sep-12 8:21am    
i used "127.0.0.1" for Host and 25 for port. but still getting error as.."Unable to connect to the remote server...." whats the prob :-/
C#
public class EmailUtility
{
    public string FromEmailID { get; set; }
    public string FromName { get; set; }
    public string ToEmailID { get; set; }
    public string CcEmailID { get; set; }
    public string BccEmailID { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
    public bool IsBodyHtml { get; set; }
    public List<String> AttachmentFiles { get; set; }
    public string Error { get; set; }

    public bool SendMail()
    {
        MailMessage mail = new MailMessage();
        try
        {
            if (!String.IsNullOrEmpty(FromEmailID))
                mail.From = new MailAddress(FromEmailID, FromName);
            else
            {
                Error = "The Sender Address can't be empty.";
                return false;
            }
            if (!String.IsNullOrEmpty(ToEmailID))
                if (ToEmailID.Contains(";"))
                {
                    string[] str = ToEmailID.Split(';');
                    for (int i = 0; i < str.Length; i++)
                        if (str[i] != String.Empty)
                            mail.To.Add(str[i]);
                }
                else
                    mail.To.Add(ToEmailID);
            else
            {
                Error = "Recepient address can't be empty.";
                return false;
            }
            if (!String.IsNullOrEmpty(BccEmailID))
                if (BccEmailID.Contains(";"))
                {
                    string[] str = BccEmailID.Split(';');
                    for (int i = 0; i < str.Length; i++)
                        if (str[i].Trim() != String.Empty)
                            mail.Bcc.Add(str[i]);
                }
                else
                    mail.Bcc.Add(BccEmailID);
            if (!String.IsNullOrEmpty(CcEmailID))
                if (CcEmailID.Contains(";"))
                {
                    string[] str = CcEmailID.Split(';');
                    for (int i = 0; i < str.Length; i++)
                        if (str[i].Trim() != String.Empty)
                            mail.CC.Add(str[i]);
                }
                else
                    mail.CC.Add(CcEmailID);
            mail.Subject = Subject;
            mail.Body = Body;
            mail.IsBodyHtml = IsBodyHtml;
            mail.Priority = MailPriority.Normal;
            if (AttachmentFiles != null)
                foreach (string attachment in AttachmentFiles)
                    mail.Attachments.Add(new Attachment(attachment, MediaTypeNames.Application.Octet));

            SmtpClient client = new SmtpClient();
            //client.EnableSsl = true;
            client.Send(mail);
            mail.Dispose();

            if (AttachmentFiles != null && AttachmentFiles.Count > 0)
                AttachmentFiles.Clear();
            return true;
        }
        catch (Exception ex)
        {
            Error = ex.ToString();
            mail.Dispose();
            return false;
        }
    }

_______________________________________________________________________

Use this Function also
_______________________________________________________________________

C#
public static EmailUtility SendActivationEmail(User user)
{
    EmailUtility utility = new EmailUtility();
    utility.FromEmailID = Utils.EmailNotification;
    utility.FromName = Utils.EmailFromName;
    utility.ToEmailID = user.Email;
    utility.Subject = "Shades n Style - New Account Activation";
    StringBuilder mailBody = new StringBuilder();
    mailBody.Append("Thank you for registering with <br/>");
    mailBody.AppendLine("Username: " + user .Email+ "<br/>");
    mailBody.AppendLine("Password: " + user.Password + "<br/><br/>");
    //mailBody.AppendLine("To complete the registration process, please click on the following link:<br/>");
    //mailBody.AppendLine(string.Format("<a href='{0}/Activate.aspx?Code={1}'>{0}/Activate.aspx?Account={1}</a> <br/><br/>", Utils.DomainName, Utils.EncryptText(user.Email)));
    mailBody.AppendLine("This message was sent from an unmonitored email address. To contact us you can use the following page: <br/>");
    mailBody.AppendLine(string.Format("<a href='{0}/contactus.aspx'>{0}/contactus.aspx</a> <br/><br/>", Utils.DomainName));
    mailBody.AppendLine("The Shades n Style Team <br/>");
    mailBody.AppendLine(string.Format("<a href='{0}'>{0}</a>", Utils.DomainName));
    utility.Body = mailBody.ToString();
    utility.IsBodyHtml = true;
    utility.SendMail();
    return utility;
}
 
Share this answer
 
v3
Comments
@nuraGGupta@ 31-Aug-10 7:00am    
Reason for my vote of 3
This is a very clumsy and difficult example for a very simple problem. This is just a copy paste of some existing code, not deliberately written or managed for this problem.
You can try using Gmail to send mail.

Just take a look at my article on it.
How to Send Mails from your GMAIL Account through VB.NET or C#. Windows Programming, with a Bit of Customization[^]

I hope this would help.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900