none
Safe body and title for sending emails with SmtpClient RRS feed

  • Question

  • Hi all,

    A quick question because after a lot of reading i can't get a clear knowledge of how to use that SmtpClient

    If i simply do that:

            string subject = TextBoxSubject.Text;           // TextBoxSubject is a regular textbox
            string body = TextBoxBody.Text;                  // TextBoxBody is a regular multiline textbox

            var smtp = new System.Net.Mail.SmtpClient();

            smtp.Host = "xxx.xxx.net";
            smtp.Port = 587;
            smtp.EnableSsl = false;
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
            smtp.Timeout = 20000;

            try
            {
                smtp.Send(fromAddress, toAddress, subject, body);

    If the user enter characters like '<' in the subject or the body of the email i get an error.

    What is the recommended way to format those strings before using them ?

    Tuesday, November 19, 2013 4:33 PM

Answers

  • It shouldn't be a problem having < characters in the subject or body. Are you sure you don't have invalid characters in the fromAddress or toAddress? If so, you typically get the error: An invalid character was found in the header".

    Also, could you try encoding the message? It shouldn't be needed in your case, but it could be worth a try. You could try do something like:

    string subject = "<Test>"; 
    string body = "<Test>"; 
    
    var mailMessage = new MailMessage(fromAddress, toAddress, subject, body);
    mailMessage.BodyEncoding = Encoding.UTF8;
    
    var smtp = new SmtpClient();
    //..
    smtp.Send(mailMessage);
    

    Also, what error message are you getting?

    • Marked as answer by Code-C Thursday, November 21, 2013 1:55 PM
    Tuesday, November 19, 2013 5:16 PM
  • You want to create MailMessage and then create the message as shown in the link below

    Your code should look something like this

        

                             MailMessage messsage = new MailMessage;

                             smtp.Send(messsage);

    http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews(v=vs.110).aspx


    jdweng

    • Marked as answer by Code-C Thursday, November 21, 2013 1:55 PM
    Tuesday, November 19, 2013 5:17 PM

All replies

  • It shouldn't be a problem having < characters in the subject or body. Are you sure you don't have invalid characters in the fromAddress or toAddress? If so, you typically get the error: An invalid character was found in the header".

    Also, could you try encoding the message? It shouldn't be needed in your case, but it could be worth a try. You could try do something like:

    string subject = "<Test>"; 
    string body = "<Test>"; 
    
    var mailMessage = new MailMessage(fromAddress, toAddress, subject, body);
    mailMessage.BodyEncoding = Encoding.UTF8;
    
    var smtp = new SmtpClient();
    //..
    smtp.Send(mailMessage);
    

    Also, what error message are you getting?

    • Marked as answer by Code-C Thursday, November 21, 2013 1:55 PM
    Tuesday, November 19, 2013 5:16 PM
  • You want to create MailMessage and then create the message as shown in the link below

    Your code should look something like this

        

                             MailMessage messsage = new MailMessage;

                             smtp.Send(messsage);

    http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews(v=vs.110).aspx


    jdweng

    • Marked as answer by Code-C Thursday, November 21, 2013 1:55 PM
    Tuesday, November 19, 2013 5:17 PM
  • thanks for your helps all ...

    I tried to encode it as you suggested, davlind but i get exactely the same error:

    -------------------------------

    Erreur du serveur dans l'application '/'.

    Une valeur Request.Form potentiellement dangereuse a été détectée à partir du client (ctl00$MainContent$Comments="aaa>aaa<qq").
      Description : ASP.NET a détecté dans la requête des données potentiellement dangereuses parce qu'elles peuvent inclure des balises ou des scripts HTML. Les données peuvent indiquer une tentative de compromission de la sécurité de votre application, telle qu'une attaque de script entre sites. Si le type de l'entrée est approprié pour votre application, vous pouvez inclure du code dans une page Web pour l'autoriser explicitement. Pour plus d'informations, consultez http://go.microsoft.com/fwlink/?LinkID=212874.

     Détails de l'exception: System.Web.HttpRequestValidationException: Une valeur Request.Form potentiellement dangereuse a été détectée à partir du client (ctl00$MainContent$Comments="aaa>aaa<qq").

    Erreur source:


     Une exception non gérée s'est produite lors de l'exécution de la requête Web actuelle. Les informations relatives à l'origine et l'emplacement de l'exception peuvent être identifiées en utilisant la trace de la pile d'exception ci-dessous. 

    Trace de la pile:

    [HttpRequestValidationException (0x80004005): Une valeur Request.Form potentiellement dangereuse a été détectée à partir du client (ctl00$MainContent$Comments="aaa>aaa<qq").]
       System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection) +12602837
       System.Web.HttpRequest.ValidateHttpValueCollection(HttpValueCollection collection, RequestValidationSource requestCollection) +132
       System.Web.HttpRequest.get_HasForm() +12605686
       System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +146
       System.Web.UI.Page.DeterminePostBackMode() +129
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +12571959
       System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +12571469
       System.Web.UI.Page.ProcessRequest() +119
       System.Web.UI.Page.ProcessRequest(HttpContext context) +99
       System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +913
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165

     


    Informations sur la version : Version Microsoft .NET Framework :4.0.30319; Version ASP.NET :4.0.30319.18033

    ------------------


    Excuse me but it is in french :-/  I use to work with all my tools in english but this is from the server that host my website.

    It's in french, but you should get the message, it looks like it is a sort of anti script security ?

    Thursday, November 21, 2013 12:50 PM
  • I'm readingi can disable that protection ( validateRequest="false" ) but i guess it would expose my website to vulnerabilities.

    Is it only that character "<" triggering this exception ?

    If yes i will simply remove it from what the user have typed and replace it with a keyword

    Thursday, November 21, 2013 12:58 PM
  • Sorry I'm talking to myself :-)

    I triggered this exception on my english local server

    --------------------

    Server Error in '/www' Application.

    A potentially dangerous Request.Form value was detected from the client (ctl00$MainContent$Comments="aaa<aaa").

    Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted.  This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack.  To allow pages to override application request validation settings, set the requestValidationMode attribute in the httpRuntime configuration section to requestValidationMode="2.0". Example: <httpRuntime requestValidationMode="2.0" />. After setting this value, you can then disable request validation by setting validateRequest="false" in the Page directive or in the <pages> configuration section.  However, it is strongly recommended that your application explicitly check all inputs in this case.  For more information, see http://go.microsoft.com/fwlink/?LinkId=153133.            

    Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (ctl00$MainContent$Comments="aaa<aaa").

    Source Error:

    The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:

    1. Add a "Debug=true" directive at the top of the file that generated the error. Example:

      <%@ Page Language="C#" Debug="true" %>

    or:

    2) Add the following section to the configuration file of your application:

    <configuration>
       <system.web>
           <compilation debug="true"/>
       </system.web>
    </configuration>

    Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.

    Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario.
                      

    Stack Trace:
    [HttpRequestValidationException (0x80004005): A potentially dangerous Request.Form value was detected from the client (ctl00$MainContent$Comments="aaa<aaa").]
       System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection) +8933716
       System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection) +122
       System.Web.HttpRequest.get_Form() +150
       System.Web.HttpRequest.get_HasForm() +9111711
       System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +97
       System.Web.UI.Page.DeterminePostBackMode() +69
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +8431
       System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +253
       System.Web.UI.Page.ProcessRequest() +78
       System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21
       System.Web.UI.Page.ProcessRequest(HttpContext context) +49
       ASP.contact_aspx.ProcessRequest(HttpContext context) +4
       System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +100
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
    

    And i noticed that page:
    http://www.asp.net/whitepapers/request-validation

    I'm reading it now, i guess i'll help myself ...
    ( I really have to better read error messages )

    Thanks for your help all

                
    Thursday, November 21, 2013 1:09 PM
  • It is Possible.  Depends if the mail message is set to HTML or Text mode.  SMTP class inherit the HTML class .  When in Text mode the the message is encapsulated in a HTML Tag and and the "<" and ">" characters will cause an error.  When in HTML mode the error is cause by a badly formed HTML message.  The "<" and ">" characters are required and there must be a corresponding open and claosed bracket.

    jdweng

    Thursday, November 21, 2013 1:10 PM
  • it's crazy, if i get it right, with this security ON, the simple fact to type a '<' in a text box raise this exception ?
    You can't even retreive the text in a regular string ?
    Thursday, November 21, 2013 1:37 PM
  • OMG all this is such a joke .... 
    basicaly, if you create a website from scratch, you put a text box and the user type "<" in that text box, this raise an exception on the server and crash the entire website .... such an elegant way to handle security ...

    I disabled all this crap, it's working fine now.

    I miss my old C++/MFC ....
    Thursday, November 21, 2013 1:54 PM