using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Net;
using
System.Net.Mail;
using
System.Net.Mime;
using
System.Text;
using
System.Windows.Forms;
namespace
Mail
{
public
partial
class
Form1 : Form
{
public
Form1()
{
InitializeComponent();
}
private
MailMessage mailMessage;
private
SmtpClient smtpClient;
private
string
password;
/// <summary>
/// 处审核后类的实例
/// </summary>
/// <param name="To">收件人地址</param>
/// <param name="From">发件人地址</param>
/// <param name="Body">邮件正文</param>
/// <param name="Title">邮件的主题</param>
/// <param name="Password">发件人密码</param>
public
void
SendMail(
string
To,
string
From,
string
Body,
string
Title,
string
Password)
{
mailMessage =
new
MailMessage();
mailMessage.To.Add(To);
mailMessage.From =
new
System.Net.Mail.MailAddress(From);
mailMessage.Subject = Title;
mailMessage.Body = Body;
mailMessage.IsBodyHtml =
true
;
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
mailMessage.Priority = System.Net.Mail.MailPriority.Normal;
this
.password = Password;
}
/// <summary>
/// 添加附件
/// </summary>
public
void
Attachments(
string
Path)
{
string
[] path = Path.Split(
','
);
Attachment data;
ContentDisposition disposition;
for
(
int
i = 0; i < path.Length; i++)
{
data =
new
Attachment(path[i], MediaTypeNames.Application.Octet);
disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(path[i]);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(path[i]);
disposition.ReadDate = System.IO.File.GetLastAccessTime(path[i]);
mailMessage.Attachments.Add(data);
}
}
/// <summary>
/// 异步发送邮件
/// </summary>
/// <param name="CompletedMethod"></param>
public
void
SendAsync(SendCompletedEventHandler CompletedMethod)
{
if
(mailMessage !=
null
)
{
smtpClient =
new
SmtpClient();
smtpClient.Credentials =
new
System.Net.NetworkCredential(mailMessage.From.Address, password);
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Host =
"smtp."
+ mailMessage.From.Host;
smtpClient.SendCompleted +=
new
SendCompletedEventHandler(CompletedMethod);
smtpClient.SendAsync(mailMessage, mailMessage.Body);
}
}
/// <summary>
/// 发送邮件
/// </summary>
public
void
Send()
{
if
(mailMessage !=
null
)
{
smtpClient =
new
SmtpClient();
smtpClient.Credentials =
new
System.Net.NetworkCredential(mailMessage.From.Address, password);
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Host =
"smtp."
+ mailMessage.From.Host;
smtpClient.Send(mailMessage);
}
}
private
void
btnSendMail_Click(
object
sender, EventArgs e)
{
try
{
this
.SendMail(
"fgzcard@21cn.com"
,
"lmm4227261@126.com"
,
this
.textBox1.Text.Trim(),
"你好"
,
"6693065"
);
this
.Send();
MessageBox.Show(
"发送成功!"
);
}
catch
(Exception myException)
{
MessageBox.Show(myException.ToString());
}
}
}
}