如何使用ASP .NET发送电子邮件 [英] How to send email using ASP .NET
问题描述
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace ProjectBuzzUtils
{
public static class EmailHelper
{
public static void SendEmail(string from, string toEmails, string ccEmails, string subject, object data, string templateType)
{
Dictionary<string, string> dataList = ExtractClassData(data);
string body = CreateEmailBody(dataList, templateType);
SendHtmlFormattedEmail(from, toEmails, ccEmails, subject, body);
}
private static string CreateEmailBody(Dictionary<string, string> replaceElement, string templateType)
{
string body = string.Empty;
var templatePath = "~/Views/EmailTemplate/" + templateType + ".cshtml";
using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(templatePath)))
{
body = reader.ReadToEnd();
foreach (var pair in replaceElement)
{
body = body.Replace(pair.Key, pair.Value);
}
}
return body;
}
private static void SendHtmlFormattedEmail(string from, string toEmails, string ccEmails, string subject, string body)
{
string fromEmail = ConfigurationManager.AppSettings["FromEmail"].ToString();
string host = ConfigurationManager.AppSettings["Host"].ToString();
SmtpClient smtpClient = new SmtpClient();
int tryAgain = 10;
bool failed = false;
do
{
try
{
failed = false;
using (MailMessage mailMessage = new MailMessage())
{
MailMessage mm = new MailMessage();
mm.Body = body;
mm.IsBodyHtml = true;
if (!string.IsNullOrEmpty(toEmails))
{
foreach (string email in toEmails.Split(','))
{
mm.To.Add(new MailAddress(email));
}
}
if (!string.IsNullOrEmpty(ccEmails))
{
foreach (string email in ccEmails.Split(','))
{
mm.CC.Add(new MailAddress(email));
}
}
mm.From = new MailAddress(from);
mm.Subject = subject;
smtpClient.Host = host;
smtpClient.Send(mm);
}
}
catch (Exception ex) // I would avoid catching all exceptions equally, but ymmv
{
failed = true;
tryAgain--;
var exception = ex.Message.ToString();
smtpClient.Dispose();
//Other code for saving exception message to a log.
}
} while (failed && tryAgain != 0);
}
public static Dictionary<string, string> ExtractClassData(object o)
{
if (o == null)
return new Dictionary<string, string>();
var type = o.GetType();
var propertyInfos = type.GetProperties()
.Select(p => new
{
Name = p.GetCustomAttribute<DisplayAttribute>() != null ? p.GetCustomAttribute<DisplayAttribute>().Name : p.Name,
FormatAttribute = p.GetCustomAttribute<DisplayFormatAttribute>(),
Property = p,
Type = p.PropertyType,
Value = p.GetValue(o),
});
var dictionary = new Dictionary<string, string>();
foreach (var property in propertyInfos.Where(p => p.Value != null))
{
if (property.Value != null)
{
dictionary.Add("$$$" + property.Name + "$$$", FormatValue(property.Value, property.Type, property.FormatAttribute));
}
}
dictionary.Add("$$$Date_String$$$", DateTime.UtcNow.AddHours(5.5).ToString());
return dictionary;
}
private static string FormatValue(object value, Type type, DisplayFormatAttribute format)
{
if (value == null)
return null;
if (type.IsEnum || (Nullable.GetUnderlyingType(type) != null && Nullable.GetUnderlyingType(type).IsEnum))
{
if (!Enum.IsDefined(type, value))
return value.ToString();
var display = type.GetField(value.ToString()).GetCustomAttribute<DisplayAttribute>();
if (display != null)
return display.Name;
return value.ToString();
}
if (type == typeof(string))
return (string)value;
if (format != null)
return string.Format(format.DataFormatString, value);
return value.ToString();
}
}
}
我是什么尝试过:
/ * ------------------------- ------------
GLOBAL RESETS
-------------------- ----------------- * /
img {
border:none;
- ms-interpolation-mode:bicubic;
max-width:100%;
}
body {
background-color:#f6f6f6;
font-family:sans-serif;
-webkit-font-smoothing:antialiased;
字体大小:14px;
行高:1.4;
保证金:0;
填充:0;
-ms-text-size-adjust:100%;
-webkit-text-size-adjust:100%;
} < br $>
table {
border-collapse:separate;
mso-table-lspace:2pt;
mso-table-rspace:2pt;
宽度:100%;
}
table td {
font-family:sans-serif;
font-size:14px ;
vertical-align:top;
}
table {
border:medium;
border-color:burlywood;
}
td tr {
border:medium;
border-color:突出显示;
}
/ * --------- ----------------------------
BODY& CONTAINER
------------------------------------- * /
.body {
background-color:#f6f6f6;
宽度:100%;
}
/ *设置一个最大宽度,并使其显示为块,这样它将自动拉伸到该宽度,但也会缩小到手机或其他东西* /
.container {
显示:阻止;
保证金:0自动!重要;
/ *使其居中* /
最大宽度:580px;
填充:10px;
宽度:580px;
}
/ *这个也应该是一个块元素,以便它将填充100%的.container * /
.content {
box-sizing:border-box;
显示:块;
保证金:0自动;
最大宽度:900px;
填充:6px;
}
/ * --------------------------- ----------
HEADER,FOOTER,MAIN
------------------- ------------------ * /
.main {
背景:#ffffff;
border-radius:3px;
宽度:100%;
}
.wrapper {
box-sizing:border-box;
padding:20px;
}
.content-block {
padding-bottom:10px;
padding-top:10px;
}
.footer {
clear:both;
Margin-top:10px;
text-align :center;
宽度:100%;
}
.footer td,
.footer p,
。页脚跨度,
.footer a {
颜色:#999999;
字体大小:12px;
text-align:center;
}
/ * ------------------------- ------------
TYPOGRAPHY
--------------------- ---------------- * /
h1,
h2,
h3,
h4 {
颜色:#000000;
font-family:sans-serif;
font-weight:400 ;
行高:1.4;
保证金:0;
保证金底部:20px;
}
h1 {
字体大小:35px;
字体重量:300;
text-align:center;
text-transform:capitalize;
}
p,
ul,
ol {
font-family:sans-serif;
font-size:14px;
font-weight:normal;
保证金:0;
保证金底部:15px;
}
p li,
ul li,
ol li {
list-style-position:inside;
margin-left:5px;
}
a {
颜色:#3498db;
文字装饰:下划线;
}
/ * - ------------------------------------
其他可能有用的款式
------------------------------------- * /
.last {
margin-bottom:0;
}
.first {
保证金 - 顶部:0;
}
.align-center {
text-align:center;
}
.align-right {
text-align:right;
} b / b
.align-left {
text-align:left;
}
.clear {
clear:both;
}
.mt0 {
margin-top:0;
}
.mb0 {
margin-bottom:0;
}
.preheader {
颜色:透明;
显示:无;
身高:0;
max-height:0;
max-width: 0;
不透明度:0;
溢出:隐藏;
mso-hide:all;
可见性:隐藏;
宽度:0;
}
.powered-一个{
text-decoration:none;
}
hr {
border:0;
border-bottom:1px solid#f6f6f6;
保证金:20px 0;
}
感谢您的反馈!
项目Buzz用户反馈
$$$日期$$$
您好,$$$员工姓名:
感谢您的反馈!
员工ID:$$$员工_Id $$$
员工姓名:$$$员工姓名$$$
员工代码:$$$员工_代码$$$
查询类型:$$$ QueryType $$$
消息:$$$消息$$$
b / b
问候,
Project Buzz W ork Flow and Production
由OPTUM SOURCE提供支持。
此电子邮件(包括附件)可能包含机密和/或专有信息,并且只能由其使用的个人或实体使用。得到解决。如果该电子邮件的读者不是预期的收件人或其授权代理人,则特此通知读者,禁止传播,分发或复制该电子邮件。如果您错误地收到了这封电子邮件,请回复此邮件通知发件人并立即删除此电子邮件。
What I have tried:
/* -------------------------------------
GLOBAL RESETS
------------------------------------- */
img {
border: none;
-ms-interpolation-mode: bicubic;
max-width: 100%;
}
body {
background-color: #f6f6f6;
font-family: sans-serif;
-webkit-font-smoothing: antialiased;
font-size: 14px;
line-height: 1.4;
margin: 0;
padding: 0;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}
table {
border-collapse: separate;
mso-table-lspace: 2pt;
mso-table-rspace: 2pt;
width: 100%;
}
table td {
font-family: sans-serif;
font-size: 14px;
vertical-align: top;
}
table {
border: medium;
border-color: burlywood;
}
td tr {
border: medium;
border-color: Highlight;
}
/* -------------------------------------
BODY & CONTAINER
------------------------------------- */
.body {
background-color: #f6f6f6;
width: 100%;
}
/* Set a max-width, and make it display as block so it will automatically stretch to that width, but will also shrink down on a phone or something */
.container {
display: block;
Margin: 0 auto !important;
/* makes it centered */
max-width: 580px;
padding: 10px;
width: 580px;
}
/* This should also be a block element, so that it will fill 100% of the .container */
.content {
box-sizing: border-box;
display: block;
Margin: 0 auto;
max-width: 900px;
padding: 6px;
}
/* -------------------------------------
HEADER, FOOTER, MAIN
------------------------------------- */
.main {
background: #ffffff;
border-radius: 3px;
width: 100%;
}
.wrapper {
box-sizing: border-box;
padding: 20px;
}
.content-block {
padding-bottom: 10px;
padding-top: 10px;
}
.footer {
clear: both;
Margin-top: 10px;
text-align: center;
width: 100%;
}
.footer td,
.footer p,
.footer span,
.footer a {
color: #999999;
font-size: 12px;
text-align: center;
}
/* -------------------------------------
TYPOGRAPHY
------------------------------------- */
h1,
h2,
h3,
h4 {
color: #000000;
font-family: sans-serif;
font-weight: 400;
line-height: 1.4;
margin: 0;
Margin-bottom: 20px;
}
h1 {
font-size: 35px;
font-weight: 300;
text-align: center;
text-transform: capitalize;
}
p,
ul,
ol {
font-family: sans-serif;
font-size: 14px;
font-weight: normal;
margin: 0;
Margin-bottom: 15px;
}
p li,
ul li,
ol li {
list-style-position: inside;
margin-left: 5px;
}
a {
color: #3498db;
text-decoration: underline;
}
/* -------------------------------------
OTHER STYLES THAT MIGHT BE USEFUL
------------------------------------- */
.last {
margin-bottom: 0;
}
.first {
margin-top: 0;
}
.align-center {
text-align: center;
}
.align-right {
text-align: right;
}
.align-left {
text-align: left;
}
.clear {
clear: both;
}
.mt0 {
margin-top: 0;
}
.mb0 {
margin-bottom: 0;
}
.preheader {
color: transparent;
display: none;
height: 0;
max-height: 0;
max-width: 0;
opacity: 0;
overflow: hidden;
mso-hide: all;
visibility: hidden;
width: 0;
}
.powered-by a {
text-decoration: none;
}
hr {
border: 0;
border-bottom: 1px solid #f6f6f6;
Margin: 20px 0;
}
Thank you for the feedback !
Project Buzz User Feedback
$$$Date$$$
Hi, $$$Employee_Name$$$
Thank you for the feedback !
Employee Id : $$$Employee_Id$$$
Employee Name : $$$Employee_Name$$$
Employee Code : $$$Employee_Code$$$
Query Type : $$$QueryType$$$
Message : $$$Message$$$
Regards,
Project Buzz Work Flow and Production
Powered by OPTUM SOURCE.
This e-mail, including attachments, may include confidential and/or proprietary information, and may be used only by the person or entity to which it is addressed. If the reader of this e-mail is not the intended recipient or his or her authorized agent, the reader is hereby notified that any dissemination, distribution or copying of this e-mail is prohibited. If you have received this e-mail in error, please notify the sender by replying to this message and delete this e-mail immediately.
推荐答案
+ property.Name +
" + property.Name + "
,FormatValue(property.Value,property.Type,property .FormatAttribute));
}
}
dictionary.Add(
", FormatValue(property.Value, property.Type, property.FormatAttribute)); } } dictionary.Add("
Date_String
Date_String
这篇关于如何使用ASP .NET发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!