简体   繁体   中英

How to send a localized email

I want to send user a localized email, but it seems the text retrieved from resource file are based on my culture.

SmtpClient client = new SmtpClient();
client.Host = "xxx.xxx.xxx";
client.Credentials = new NetworkCredential("name", "password");
MailMessage mm = new MailMessage();
mm.Sender = new MailAddress("xxx@xxx.com");
mm.From = new MailAddress("xxx@xxx.com");
mm.To.Add(new MailAddress(email));
mm.Subject = Localization.EmailUserActiveTitle;
mm.Body = "<div><h3>" + Localization.EmailUserActiveBodyPart1 + "</h3></div></br>" +
            "<div>" + Localization.EmailUserActiveBodyPart2 + "</div>" +
            "<div><b>" + content + "</b></div></br>" +
            "<div>" + Localization.EmailUserActiveBodyPart3 + "</div>" +
            "<div>" + Localization.EmailUserActiveBodyPart4 + "</div>";
mm.IsBodyHtml = true;
mm.Priority = MailPriority.Normal;
client.Send(mm);

But when i retrieve Localization.EmailUserActiveBodyPart1 it is localized base on my current culture.

how can i retrieve specified culture resource file?

The ResourceManager uses the Thread.CurrentThread.CurrentUICulture property to determine which localized language version of a resource to load.

So if you want to force localization to a specific language (eg the language preference associated with the user you are sending email to), then just do this before your code:

var previousUICulture = Thread.CurrentThread.CurrentUICulture;
Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR"); // Replace with the relevant culture name for your user

And clean up* just after your code:

Thread.CurrentThread.CurrentUICulture = previousUICulture;

*Obviously this is not a reliable clean-up. A finally block or wrapping this language-switching functionality in an IDisposable and using a using block would prevent your code running in a random language in case of a failure, but that's outside the point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM