ASP.NET MVC Email

后端 未结 7 1111
日久生厌
日久生厌 2021-01-30 11:50

Is their a solution to generate an email template using an ASP.NET MVC View without having to jump through hoops.

Let me elaborate jumping through hoops.



        
7条回答
  •  无人及你
    2021-01-30 12:22

    If you want simple text replacements, .NET has something for that:

            ListDictionary replacements = new ListDictionary();
    
            // Replace hard coded values with objects values
            replacements.Add("{USERNAME}", "NewUser");            
            replacements.Add("{SITE_URL}", "http://yourwebsite.com");
            replacements.Add("{SITE_NAME}", "My site's name");
    
            string FromEmail= "from@yourwebsite.com";
            string ToEmail = "newuser@gmail.com";
    
            //Create MailDefinition
            MailDefinition md = new MailDefinition();
    
            //specify the location of template
            md.BodyFileName = "~/Templates/Email/Welcome.txt";
            md.IsBodyHtml = true;
            md.From = FromEmail;
            md.Subject = "Welcome to youwebsite.com ";
    
            System.Web.UI.Control ctrl = new System.Web.UI.Control { ID = "IDontKnowWhyThisIsRequiredButItWorks" };
    
            MailMessage message = md.CreateMailMessage(ToEmail , replacements, ctrl);
    
            //Send the message
            SmtpClient client = new SmtpClient();
    
            client.Send(message);
    

    And the Welcome.txt file

        Welcome - {SITE_NAME}

    Thank you for registering at {SITE_NAME}

    Your account is activated and ready to go!
    To login, visit {SITE_NAME} and use the following credentials:
    username: {USERNAME}
    password: use the password you registered with

    - {SITE_NAME} Team

    Again, this is only good for simple string replacements. If you plan emailing more data, you would need to format it properly then replace it.

提交回复
热议问题