您的位置:首页 > 编程语言 > C#

用C#发送邮件的编程方法及实例代码分享

2013-04-19 10:33 761 查看
用C#发送邮件的编程方法及实例代码分享

在此分享一个c#发送邮件的实例代码,代码是亲自写出来,而且也亲测过气动阀门,可以正常发送邮件。希望对大家有所帮助!

为了方便使用,麦子把发邮件的核心代码提取为一个气动阀门类(Mail),

代码如下:

01
using
System;
02
using
System.Collections.Generic;
03
using
System.Linq;
04
using
System.Text;
05
using
System.Net.Mail;
06
using
System.ComponentModel;
07
using
System.Windows.Forms;
08
using
System.Net;
09
10
namespace
com.ykmaiz.email
11
{
12
public
class
Mail
13
{
14
private
string
username =
""
;
15
private
string
password =
""
;
16
private
string
domain =
""
;
17
public
Mail(
string
username,
string
password,
string
domain)
18
{
19
this
.username =username;
20
this
.password =password;
21
this
.domain =domain;
22
}
23
public
void
send(
string
from,
string
[] to,
string
[] cc,
string
title,
string
content)
24
{
25
MailMessage mailMsg =
new
MailMessage();
26
mailMsg.From =
new
MailAddress(from);
27
if
(to.Length > 0)
28
{
29
foreach
(
string
s
in
to)
30
{
31
mailMsg.To.Add(s);
32
}
33
}
34
if
(cc.Length > 0)
35
{
36
foreach
(
string
s
in
cc)
37
{
38
mailMsg.CC.Add(s);
39
}
40
}
41
mailMsg.Subject = title;
42
mailMsg.Body = content;
43
mailMsg.BodyEncoding = Encoding.UTF8;
44
mailMsg.IsBodyHtml =
false
;
45
mailMsg.Priority = MailPriority.High;
46
SmtpClient smtp =
new
SmtpClient();
47
smtp.Credentials= 
new
NetworkCredential(username,password);
48
smtp.Port = 25;
49
smtp.Host = domain;
50
smtp.EnableSsl =
false
;
51
smtp.SendCompleted +=
new
SendCompletedEventHandler(SendMailCompleted);
52
try
53
{
54
smtp.SendAsync(mailMsg,mailMsg);
55
}
56
catch
(SmtpException ex)
57
{
58
Console.WriteLine(ex.ToString());
59
}
60
}
61
}
62
}
然后直接调用气动阀门该类的send()方法即可,

实例代码如下:

1
Mail mail =
new
Mail(
"发邮件的地址"
,
"发邮件的密码"
,
"邮件的smtp地址"
);
2
3
mail.send(
"发邮件的地址"
,
new
string
[] {
"收件人地址"
},
new
string
[] {
"抄送人地址"
},
"邮件标题"
,
"邮件内容"
);
很方便,赶快去试试吧!

以后会陆续更新我的气动阀门经验分享,请多关注!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: