Tech Off Thread

7 posts

Asp mail in code behind

Back to Forum: Tech Off
  • User profile image
    lesmemphis

    Hey,

     

    I need to send info from a contact page to both administrator and also the client (if send copy checkbox is checked). It is an aspx page, and my code keeps bombing. Could someone look for a problem in my code? (also, maybe the problem lies with the server?)

     

    protected void ButtonSubmit_Click(object sender, EventArgs e)
            {
                if (Page.IsValid)//if captcha is entered correctly, this will be true
                {
                    bool error = false;
                    if (TextBoxSurname.Text == "")
                    {
                        LabelSurnameError.Visible = true;
                        error = true;
                    }
                    else
                    {
                        LabelSurnameError.Visible = false;
                    }
                    if (TextBoxEmail.Text == "")
                    {
                        LabelEmailError.Visible = true;
                        error = true;
                    }
                    else
                    {
                        LabelEmailError.Visible = false;
                    }
                    if (TextBoxEmail.Text != TextBoxConfirmEmail.Text)
                    {
                        LabelConfirmEmailError.Visible = true;
                        error = true;
                    }
                    else
                    {
                        LabelConfirmEmailError.Visible = false;
                    }
                    if (TextBoxEnquiry.Text == "")
                    {
                        LabelEnquiryError.Visible = true;
                        error = true;
                    }
                    else
                    {
                        LabelEnquiryError.Visible = false;
                    }
                    if (error == true)
                        return;

                    MailMessage msg = new MailMessage(TextBoxEmail.Text, "juan.venter@hotmail.com");
                    msg.Subject = "Backpackers portal Enquiry";

                    if (CheckBoxCopy.Checked)
                    {
                        msg.Bcc.Add(TextBoxEmail.Text);
                    }

                    msg.Body = "Submitted By: " + DropDownListTitle.Text + " " + TextBoxSurname.Text + "\n";

                    if (TextBoxFirstname.Text != "")
                    {
                        msg.Body += "Firstname : " + TextBoxFirstname.Text + "\n";
                    }
                    if (TextBoxContactNum.Text != "")
                    {
                        msg.Body += "Contact Number : " + TextBoxContactNum.Text + "\n";
                    }
                    if (TextBoxCell.Text != "")
                    {
                        msg.Body += "Cell Number : " + TextBoxCell.Text + "\n";
                    }

                    msg.Body += "Enquiry : " + TextBoxEnquiry.Text;

                    SmtpClient sm = new SmtpClient();
                    sm.Host = "196.22.134.22";
                    sm.Send(msg);

                    //Response.Write("<script>");
                    //Response.Write("Set myMail=CreateObject('CDO.Message')");
                    //Response.Write("myMail.Subject='Sending email with CDO'");
                    //Response.Write("myMail.From='juan.venter@hotmail.com'");
                    //Response.Write("myMail.To='juan@semper.co.za'");
                    //Response.Write("myMail.TextBody='This is a message.'");
                    //Response.Write("myMail.Send");
                    //Response.Write("set myMail=nothing");
                    //Response.Write("</script>");
                }
            }

     

    Thanks!!!! Angel

  • User profile image
    W3bbo

    What's the error?

     

    Your code looks fine (though your validation code could easily be refactored and shortened).

  • User profile image
    figuerres

    can you view event logs on the server that runs the code ?

    if you can then look at the .net asp.net config docs and send errors to the event log.

     

    that way you can log the error.

    when you have things fixed later you can put in a custom error page to showe users

     

    but as for it not working do you know how to use telnet to check the mail server out?

    try to telnet the smtp server and see if that works, port 25 and all that...

     

    my first guess is that the smtp server needs auth before send and i do not see any smtp auth in your code.

    thats a common issue as smtp servers that are not an open relay need to authenticate the sender before they take any other input.

     

    also i do not have the docs at hand - whats the "from" address is it that hotmail one i see in the code ??

    is the ip for a hotmail server ?

     

    if not then you may fail on the relay tests as the sender is not on the smtp servers domain and the recipient is not.

    that makes it a relay and again most mail servers do not relay.

     

    also when i send mail i try/catch on mail server errors as some are just a need to wait 30 seconds and try again.

     

    later i can possibly post a small bit on what i do from a windows service that works really well and could also be used for a web page.

     

  • User profile image
    figuerres

    figuerres said:

    can you view event logs on the server that runs the code ?

    if you can then look at the .net asp.net config docs and send errors to the event log.

     

    that way you can log the error.

    when you have things fixed later you can put in a custom error page to showe users

     

    but as for it not working do you know how to use telnet to check the mail server out?

    try to telnet the smtp server and see if that works, port 25 and all that...

     

    my first guess is that the smtp server needs auth before send and i do not see any smtp auth in your code.

    thats a common issue as smtp servers that are not an open relay need to authenticate the sender before they take any other input.

     

    also i do not have the docs at hand - whats the "from" address is it that hotmail one i see in the code ??

    is the ip for a hotmail server ?

     

    if not then you may fail on the relay tests as the sender is not on the smtp servers domain and the recipient is not.

    that makes it a relay and again most mail servers do not relay.

     

    also when i send mail i try/catch on mail server errors as some are just a need to wait 30 seconds and try again.

     

    later i can possibly post a small bit on what i do from a windows service that works really well and could also be used for a web page.

     

    the following is used with a local smtp server i run. it has a private lan rule for sending mail.

    after this i will paste some other code that does smtp auth before sending.

     

     
    public class SendEmail { 
    public System.Diagnostics.EventLog MyLog { get; set; }
     public string ServerName { get; set; } 
    public string Subject { get; set; } 
    public string Body { get; set; } 
    public string From { get; set; } 
    public List<string> CC { get; set; } 
    public List<string> BCC { get; set; } 
    public List<string> TO { get; set; } 
    public MailPriority PriorityOption { get; set; } 
    public NetworkCredential Credential { get; set; } 
    public bool IsBodyHTML { get; set; } 
    public void Send() { 
    try { 
    SmtpClient Mail = new SmtpClient(ServerName); 
    MailMessage Msg = new MailMessage(); 
    Msg.Subject = Subject; 
    Msg.Body = Body; 
    Msg.From = new MailAddress(From); 
    Msg.Sender = new MailAddress(From); 
    foreach (var item in TO) { 
    Msg.To.Add(new MailAddress(item));
     }
     if (CC != null) { 
    foreach (var item in CC) {
     Msg.CC.Add(new MailAddress(item));
     } 
    } 
    if (BCC != null) {
     foreach (var item in BCC) {
     Msg.Bcc.Add(new MailAddress(item)); 
    } 
    } 
    Msg.IsBodyHtml = IsBodyHTML; 
    Msg.Priority = PriorityOption;
     if (Credential != null) {
     Mail.Credentials = Credential; 
    } 
    try { 
    Mail.Send(Msg); 
    Mail = null;
     } catch (SmtpFailedRecipientsException Srep) { 
    for (int i = 0 ; i < Srep.InnerExceptions.Length ; i++) {
     SmtpStatusCode status = Srep.InnerExceptions[i].StatusCode; 
    if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable) {
     MyLog.WriteEntry("Delivery failed - retrying in 5 seconds.", EventLogEntryType.Information); 
    System.Threading.Thread.Sleep(5000);
     Mail.Send(Msg); Mail = null; 
    } else { 
    MyLog.WriteEntry(string.Format("Failed to deliver message to {0} SMTP Status Code {1}", Srep.InnerExceptions[i].FailedRecipient, status.ToString()), EventLogEntryType.Error); 
    } 
    }
     } catch (SmtpException ExS) {
     if (ExS.StatusCode == SmtpStatusCode.ServiceNotAvailable) {
     MyLog.WriteEntry("Delivery failed, ServiceNotAvailable - retrying in 5 seconds.", EventLogEntryType.Information); System.Threading.Thread.Sleep(5000);
     Mail.Send(Msg); Mail = null;
     } else { 
    MyLog.WriteEntry("SmtpException Msg: " + ExS.Message + "\nSource : " + ExS.Source + "\nStack: " + ExS.StackTrace + "\nStatus: " + ExS.StatusCode.ToString() + "\n" + (ExS.InnerException != null ? "InnerEx.Msg: " + ExS.InnerException.Message : ""), EventLogEntryType.Error); 
    //MyLog.WriteEntry(string.Format("Failed to deliver message SMTP Status Code {0}",ExS.StatusCode.ToString()), EventLogEntryType.Error); 
    }
     } catch (Exception Ex) {
     MyLog.WriteEntry("Send Mail: " + Ex.Message + " \n" + Ex.Source + "\n" + Ex.StackTrace + "\n" + (Ex.InnerException != null ? Ex.InnerException.Message : ""), EventLogEntryType.Error);
     } 
    } catch (Exception Ex) { 
    MyLog.WriteEntry("Send Mail: " + Ex.Message + " \n" + Ex.Source + "\n" + Ex.StackTrace + "\n" + (Ex.InnerException != null ? Ex.InnerException.Message : ""), EventLogEntryType.Error);
     } 
    } 
    }

  • User profile image
    figuerres

    figuerres said:
    figuerres said:
    *snip*

    the following is used with a local smtp server i run. it has a private lan rule for sending mail.

    after this i will paste some other code that does smtp auth before sending.

     

     
    public class SendEmail { 
    public System.Diagnostics.EventLog MyLog { get; set; }
     public string ServerName { get; set; } 
    public string Subject { get; set; } 
    public string Body { get; set; } 
    public string From { get; set; } 
    public List<string> CC { get; set; } 
    public List<string> BCC { get; set; } 
    public List<string> TO { get; set; } 
    public MailPriority PriorityOption { get; set; } 
    public NetworkCredential Credential { get; set; } 
    public bool IsBodyHTML { get; set; } 
    public void Send() { 
    try { 
    SmtpClient Mail = new SmtpClient(ServerName); 
    MailMessage Msg = new MailMessage(); 
    Msg.Subject = Subject; 
    Msg.Body = Body; 
    Msg.From = new MailAddress(From); 
    Msg.Sender = new MailAddress(From); 
    foreach (var item in TO) { 
    Msg.To.Add(new MailAddress(item));
     }
     if (CC != null) { 
    foreach (var item in CC) {
     Msg.CC.Add(new MailAddress(item));
     } 
    } 
    if (BCC != null) {
     foreach (var item in BCC) {
     Msg.Bcc.Add(new MailAddress(item)); 
    } 
    } 
    Msg.IsBodyHtml = IsBodyHTML; 
    Msg.Priority = PriorityOption;
     if (Credential != null) {
     Mail.Credentials = Credential; 
    } 
    try { 
    Mail.Send(Msg); 
    Mail = null;
     } catch (SmtpFailedRecipientsException Srep) { 
    for (int i = 0 ; i < Srep.InnerExceptions.Length ; i++) {
     SmtpStatusCode status = Srep.InnerExceptions[i].StatusCode; 
    if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable) {
     MyLog.WriteEntry("Delivery failed - retrying in 5 seconds.", EventLogEntryType.Information); 
    System.Threading.Thread.Sleep(5000);
     Mail.Send(Msg); Mail = null; 
    } else { 
    MyLog.WriteEntry(string.Format("Failed to deliver message to {0} SMTP Status Code {1}", Srep.InnerExceptions[i].FailedRecipient, status.ToString()), EventLogEntryType.Error); 
    } 
    }
     } catch (SmtpException ExS) {
     if (ExS.StatusCode == SmtpStatusCode.ServiceNotAvailable) {
     MyLog.WriteEntry("Delivery failed, ServiceNotAvailable - retrying in 5 seconds.", EventLogEntryType.Information); System.Threading.Thread.Sleep(5000);
     Mail.Send(Msg); Mail = null;
     } else { 
    MyLog.WriteEntry("SmtpException Msg: " + ExS.Message + "\nSource : " + ExS.Source + "\nStack: " + ExS.StackTrace + "\nStatus: " + ExS.StatusCode.ToString() + "\n" + (ExS.InnerException != null ? "InnerEx.Msg: " + ExS.InnerException.Message : ""), EventLogEntryType.Error); 
    //MyLog.WriteEntry(string.Format("Failed to deliver message SMTP Status Code {0}",ExS.StatusCode.ToString()), EventLogEntryType.Error); 
    }
     } catch (Exception Ex) {
     MyLog.WriteEntry("Send Mail: " + Ex.Message + " \n" + Ex.Source + "\n" + Ex.StackTrace + "\n" + (Ex.InnerException != null ? Ex.InnerException.Message : ""), EventLogEntryType.Error);
     } 
    } catch (Exception Ex) { 
    MyLog.WriteEntry("Send Mail: " + Ex.Message + " \n" + Ex.Source + "\n" + Ex.StackTrace + "\n" + (Ex.InnerException != null ? Ex.InnerException.Message : ""), EventLogEntryType.Error);
     } 
    } 
    }

    if the server is remote and or if you need to auth before send then use this:

     

    SendEmail SM = new SendEmail();

    SM.ServerName = "smtp.domain.com";
             SM.Credential = new NetworkCredential(sendinguser@domain.com, "SecretPassword");

    replace server name and other values as needed.

  • User profile image
    lesmemphis

    figuerres said:
    figuerres said:
    *snip*

    if the server is remote and or if you need to auth before send then use this:

     

    SendEmail SM = new SendEmail();

    SM.ServerName = "smtp.domain.com";
             SM.Credential = new NetworkCredential(sendinguser@domain.com, "SecretPassword");

    replace server name and other values as needed.

    Thanks for the advice! Worked great!!!!

  • User profile image
    figuerres

    lesmemphis said:
    figuerres said:
    *snip*

    Thanks for the advice! Worked great!!!!

    Glad to help....  I use that same code in like 3 different services to send many emails....

    if you use the asp.net event log setup you can also send the event log info like my code does...

     

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.