Search code examples
c#asp.netsystem.net.mail

Can't send mail in ASP.NET?


Guys I am trying to send an email using the code below in ASP.net but it is not working. However, the same code works for win forms. I am using c#. What seems to be the problem?

    try
    {
        using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage())
        {
            message.To.Add("//some id");
            message.Subject = "New Ticket Generated";
            message.From = new System.Net.Mail.MailAddress("//id");
            message.IsBodyHtml = true;
            message.Body = "This is message body";

            using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient())
            {
                smtp.Host = "// smtp host";
                smtp.Credentials = new System.Net.NetworkCredential("// username", "// pass");
                smtp.Send(message);
            }
         }
    }
    catch { }

Solution

  • i think you have missed some codes to write to work it in asp.net

    codes are
    smtp.Port = "port number";
    smtp.EnableSsl = true;
    smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
    smtp.UseDefaultCredentials = false;
    

    follow these are some codes which may help you

    try
        {
            using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage())
            {
                message.To.Add("to emailadress");
                message.Subject = "New Ticket Generated";
                message.From = new System.Net.Mail.MailAddress("from emailaddress");
                message.IsBodyHtml = true;
                message.Body = "This is message body";
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 25;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential("yourEmailid", "yourpassword");
                smtp.Send(message);
    
            }
        }
        catch(Exception)
        {
            throw;
        }
    

    N.B- here i am using gmail smtp server and port, for that you must use an gmail Email address in "from emailaddress" and in smtp.Credentials = new System.Net.NetworkCredential("the same email-id from emailaddress", "the password of the from emailaddress ");

    for example

    message.From = new System.Net.Mail.MailAddress("[email protected]");
    smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "myp@ssword");
    

    follow this link to get reference of all smtp server details http://www.arclab.com/en/amlc/list-of-smtp-and-pop3-servers-mailserver-list.html

    try it and goodluck