asp.net发送E-mail

简介:

发送电子邮件也是项目开发当中经常用到的功能,这里我整理了一个发送电子邮件(带附件,支持多用户发送,主送、抄送)的类库,供大家参考。

先上两个实体类,用于封装成Mail对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/// <summary>
/// 发送邮件请求
/// </summary>
public  class  MailRequest
{
     #region PrivateFields
                          
     /// <summary>
     /// 文件名
     /// </summary>
     private  string  _fromField;
                          
     /// <summary>
     /// 返送到
     /// </summary>
     private  string  _toField;
                          
     /// <summary>
     /// 抄送
     /// </summary>
     private  string  _copyField;
                          
     /// <summary>
     /// 附件
     /// </summary>
     private  string  _bccField;
                          
     /// <summary>
     /// 标题
     /// </summary>
     private  string  _subjectField;
                          
     /// <summary>
     /// 发送人名
     /// </summary>
     private  string  _bodyField;
                          
     /// <summary>
     /// 类容
     /// </summary>
     private  MailRequestAttachments[] _attachmentsField;
                         
     #endregion
                          
     /// <summary>
     /// 发送人,多个人以分号;间隔
     /// </summary>
     public  string  From
     {
         get
         {
             return  this ._fromField;
         }
                          
         set
         {
             this ._fromField = value;
         }
     }
                          
     /// <summary>
     /// 收件人,多个人以分号;间隔
     /// </summary>
     public  string  To
     {
         get
         {
             return  this ._toField;
         }
                          
         set
         {
             this ._toField = value;
         }
     }
                          
     /// <summary>
     /// 抄送人,多个人以分号;间隔
     /// </summary>
     public  string  CC
     {
         get
         {
             return  this ._copyField;
         }
                          
         set
         {
             this ._copyField = value;
         }
     }
                          
     /// <summary>
     /// 秘密抄送人,多个人以分号;间隔
     /// </summary>
     public  string  Bcc
     {
         get
         {
             return  this ._bccField;
         }
                          
         set
         {
             this ._bccField = value;
         }
     }
                          
     /// <summary>
     /// 主题
     /// </summary>
     public  string  Subject
     {
         get
         {
             return  this ._subjectField;
         }
                          
         set
         {
             this ._subjectField = value;
         }
     }
                          
     /// <summary>
     /// 内容
     /// </summary>
     public  string  Body
     {
         get
         {
             return  this ._bodyField;
         }
                          
         set
         {
             this ._bodyField = value;
         }
     }
                          
     /// <summary>
     /// 附件列表
     /// </summary>
     public  MailRequestAttachments[] Attachments
     {
         get
         {
             return  this ._attachmentsField;
         }
                          
         set
         {
             this ._attachmentsField = value;
         }
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/// <summary>
/// 发送邮件请求附件
/// </summary>
public  class  MailRequestAttachments
{
     #region PrivateFields
                        
     /// <summary>
     /// 文件名
     /// </summary>
     private  string  _fileNameField;
                        
     /// <summary>
     /// 文件内容
     /// </summary>
     private  byte [] _fileDataField;
                       
     #endregion
                        
     /// <summary>
     /// 文件名
     /// </summary>
     public  string  FileName
     {
         get
         {
             return  this ._fileNameField;
         }
                        
         set
         {
             this ._fileNameField = value;
         }
     }
                        
     /// <summary>
     /// 文件内容
     /// </summary>
     public  byte [] FileData
     {
         get
         {
             return  this ._fileDataField;
         }
                        
         set
         {
             this ._fileDataField = value;
         }
     }
}

附件的内容很简单,因为在网络传输当中,是以字节流的形式传输的,因此附件的传输需要转换成字节流数组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/// <summary>
/// 邮件帮助类
/// </summary>
public  static  class  MailHelper
{
     /// <summary>
     /// 发送邮件
     /// </summary>
     /// <param name="request">邮件内容对象</param>
     /// <returns>发送邮件所遇到的异常</returns>
     public  static  string  SendMail(MailRequest request)
     {
         try
         {
             MailMessage mail =  new  MailMessage();
                   
             if  ( string .IsNullOrEmpty(request.From))
             {
                 request.From = WebConfigurationManager.AppSettings[ "DefaultMailFrom" ];
             }
             mail.From =  new  MailAddress(request.From);
                   
             PaserMailAddress(request.To, mail.To);
             PaserMailAddress(request.CC, mail.CC);
             PaserMailAddress(request.Bcc, mail.Bcc);
                   
             mail.Subject = request.Subject;
             mail.SubjectEncoding = System.Text.Encoding.UTF8;
             mail.Body = request.Body;
             mail.ReplyTo =  new  MailAddress(request.From);
             mail.IsBodyHtml =  true ;
                   
             if  (request.Attachments !=  null  && request.Attachments.Length > 0)
             {
                 for  ( int  i = 0; i < request.Attachments.Length; i++)
                 {
                     Attachment mailAttach =  new  Attachment(ByteArrayToStream(request.Attachments[i].FileData), request.Attachments[i].FileName);
                   
                     mail.Attachments.Add(mailAttach);
                 }
             }
                   
             if  ( string .IsNullOrEmpty(WebConfigurationManager.AppSettings[ "SMTPSERVER" ]))
             {
                 throw  new  ApplicationException( "邮件服务无效" );
             }
                   
             //Smtp Server
             SmtpClient mailClient =  new  SmtpClient(WebConfigurationManager.AppSettings[ "SMTPSERVER" ]);
                   
             if  (! string .IsNullOrEmpty(WebConfigurationManager.AppSettings[ "SMTPSERVERPORT" ]))
             {
                 //端口号
                 try
                 {
                     mailClient.Port = Int32.Parse(WebConfigurationManager.AppSettings[ "SMTPSERVERPORT" ]);
                 }
                 catch
                 {
                     return  "SMTP服务器端口设置错误,端口必须设置为数值型" ;
                 }
             }
                   
             if  (! string .IsNullOrEmpty(WebConfigurationManager.AppSettings[ "MAILUSER" ]))
             {
                 mailClient.Credentials =  new  System.Net.NetworkCredential(WebConfigurationManager.AppSettings[ "MAILUSER" ], WebConfigurationManager.AppSettings[ "MAILUSERPW" ]);
                 mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
             }
             else
             {
                 mailClient.Credentials = CredentialCache.DefaultNetworkCredentials;
             }
                   
             mailClient.Send(mail);
             mail.Dispose();
                   
             return  "邮件发送成功。" ;
         }
         catch  (SmtpFailedRecipientsException e)
         {
             return  e.Message;
         }
         catch  (SmtpFailedRecipientException e)
         {
             return  e.Message;
         }
         catch  (SmtpException e)
         {
             return  e.Message;
         }
         catch  (Exception e)
         {
             return  e.Message;
         }
     }
                   
     /// <summary>
     /// 解析分解邮件地址
     /// </summary>
     /// <param name="mailAddress">邮件地址</param>
     /// <param name="mailCollection">邮件对象</param>
     private  static  void  PaserMailAddress( string  mailAddress, MailAddressCollection mailCollection)
     {
         if  ( string .IsNullOrEmpty(mailAddress))
         {
             return ;
         }
                   
         char [] separator =  new  char [2] {  ',' ';'  };
         string [] addressArray = mailAddress.Split(separator);
                   
         foreach  ( string  address  in  addressArray)
         {
             if  (address.Trim() ==  string .Empty)
             {
                 continue ;
             }
                   
             mailCollection.Add( new  MailAddress(address));
         }
     }
                   
     /// <summary>
     /// 字节数组转换为流
     /// </summary>
     /// <param name="byteArray">字节数组</param>
     /// <returns>Stream</returns>
     private  static  Stream ByteArrayToStream( byte [] byteArray)
     {
         MemoryStream mstream =  new  MemoryStream(byteArray);
                   
         return  mstream;
     }
}

这是一个邮件助手类,定义成static,无需实例化,直接类名.方法名的形式调用。

只需要上述3个类就可以实现发送Email了,由于上面引用的是web.config里面的信息(asp.net等命名空间,如果是winform等需要自己修改一下),这里还需要配置一下web.config,如下所示:

1
2
3
4
5
6
7
8
9
< appSettings >
   <!--邮件发送配置-->
   < add  key = "SMTPSERVER"  value = "smtp.qq.com" />
   <!--这是服务器邮箱的地址,如果是新浪,则填 smtp.sina.com-->
   < add  key = "MAILUSER"  value = "xxx" />
   <!--注意!这是对应服务器邮箱的账号-->
   < add  key = "MAILUSERPW"  value = "yyy" />
   <!--注意!这是对应服务器邮箱的账号密码-->
</ appSettings >

最后上一个测试方法,在主函数当中或者Page_Load事件中执行即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private  void  SendEmailExample()
{
     MailRequest mail =  new  MailRequest();
     mail.Subject =  "hello,this is a e-mail sent by asp.net mailhelper." ; //主题
     mail.Body =  "hello,this is a e-mail sent by asp.net mailhelper.<a href='http://blog.csdn.net/guwei4037'>欢迎访问我的博客。</a>" ;//内容
     mail.Bcc =  "512122338@qq.com" ; //秘密抄送人
     mail.From =  "345822155@qq.com" ; //发送人
     mail.CC =  "guwei4037@sina.com" ; //抄送人
     mail.To =  "guwei4037@gmail.com" ; //收件人
        
     //读取文件到bytes
     FileStream stream =  new  FileStream(Path.Combine(Server.MapPath( "~" ),  "doc\\test.txt" ), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
     byte [] bytes =  new  byte [stream.Length];
     stream.Read(bytes, 0, bytes.Length);
     stream.Close();
        
     //附件
     MailRequestAttachments attachments =  new  MailRequestAttachments();
     attachments.FileName =  "test.txt" ;
     attachments.FileData = bytes;
     mail.Attachments =  new  MailRequestAttachments[] {
             attachments
         };
        
     string  sendMainResult =  "-1" ;
     if  (! string .IsNullOrEmpty(mail.CC.Replace( ";" "" )) && ! string .IsNullOrEmpty(mail.To.Replace( ";" "" )))
     {
         sendMainResult = MailHelper.SendMail(mail);
     }
     Response.Write(sendMainResult);
}

发送邮件成功,附件也能正常打开,而且多个用户都收到了电子邮件。截图为证。


Center

源代码下载,请点击这里。




本文转自 guwei4037  51CTO博客,原文链接:http://blog.51cto.com/csharper/1345981

相关文章
|
.NET 开发框架 数据安全/隐私保护
|
.NET C# 数据安全/隐私保护
|
.NET 开发框架 数据安全/隐私保护
asp.net发送E-mail
发送电子邮件也是项目开发当中经常用到的功能,这里我整理了一个发送电子邮件(带附件,支持多用户发送,主送、抄送)的类库,供大家参考。
1196 0
|
.NET 开发框架 数据安全/隐私保护
asp.net发送E-mail
发送电子邮件也是项目开发当中经常用到的功能,这里我整理了一个发送电子邮件(带附件,支持多用户发送,主送、抄送)的类库,供大家参考。
760 0
|
.NET 开发框架
ASP.NET中发送邮件
private void btnSubmit_Click(object sender, System.EventArgs e){ //SmtpMail.Send("shaozhd@263.net","shaozhd@263.
792 0
|
2月前
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
37 7
|
2月前
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
52 0
|
3月前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
44 0