LoginSignup
4
5

More than 5 years have passed since last update.

ASP.NET > ASP.NETからRazorEngineを使いメール送信する

Last updated at Posted at 2016-03-17

以下に解説があるような、ないような・・・
http://mehdi.me/generating-html-emails-with-razorengine-basics-generating-your-first-email/

以下のサンプルAPPを参考に
https://github.com/mehdime/RazorEngineEmails

RazorEngineのバージョンは3.4でした。
V3.5は
TemplateService→RazorEngineServiceへと推奨が変わっており、
RazorEngineServiceを使うほうがどうやらいいみたい。


public static void StronglyTypedModel_RazorEngineService(string welcomeEmailTemplatePath)
{
    var config = new TemplateServiceConfiguration();
    config.Language = Language.CSharp; // VB.NET as template language.
    //config.EncodedStringFactory = new RawStringFactory(); // Raw string encoding.
    config.EncodedStringFactory = new HtmlEncodedStringFactory(); // Html encoding.\


    var service = RazorEngineService.Create(config);
    Engine.Razor = service;


    // Generate the email body from our email template
    var stronglyTypedModel = new UserModel() { Name = "Sarah", Email = "sarah@mail.example", IsPremiumUser = false };


   // string template = "Hello @Model.Name, welcome to RazorEngine!";
    string templateFile = welcomeEmailTemplatePath;
    var template = new LoadedTemplateSource(File.ReadAllText(templateFile), templateFile);
    var result = Engine.Razor.RunCompile(template, "templateKey", null, stronglyTypedModel);


    // Send the email
    var email = new MailMessage()
    {
        Body = result,
        IsBodyHtml = true,
        Subject = "Welcome (generated from strongly-typed model)"
    };

    email.To.Add(new MailAddress(stronglyTypedModel.Email, stronglyTypedModel.Name));

    var smtpClient = new SmtpClient();
    smtpClient.Send(email);

    service.Dispose();
}

送信元のアドレスやSMTPの定義はどこで?と思ったらApp.configで設定するみたいです。
```xml
<?xml version="1.0" encoding="utf-8" ?>



<system.net>
    <mailSettings>
        <!-- Use the optional 'from' attribute to specify a default sender name and email if none is set in code -->
        <smtp deliveryMethod="Network" from="John &lt;john@awesomesite.com&gt;">
            <network host="localhost" />
        </smtp>
    </mailSettings>
</system.net>


```

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5