当前位置:文档之家› SMTP协议发送电子邮件 源代码

SMTP协议发送电子邮件 源代码

namespace SMTPServer

{

public partial class sendMailTSMI : Form

{

public sendMailTSMI()

{

InitializeComponent();

}

private void sendMailTSMI_Load(object sender, EventArgs e) {

fromTxt.Text = SendMail.mailFrom;

prptComBox.SelectedIndex = 0;

rBtnHTML.Checked = true;

}

private void button1_Click(object sender, EventArgs e)//浏览按钮

{

OpenFileDialog oFileDialog = new OpenFileDialog();

if (oFileDialog.ShowDialog() == DialogResult.OK)

{

AttachTxt.Text = oFileDialog.FileName;

}

}

private void btnSend_Click(object sender, EventArgs e)//发送按钮

{

if (toTxt.Text.Trim() == "")

{

MessageBox.Show("收件人不能为空!");

return;

}

if (fromTxt.Text.Trim() == string.Empty)

{

MessageBox.Show("发件人不能为空!");

return;

}

string mailTo = toTxt.Text.Trim();

string mailCC = ccTxt.Text.Trim();

string mailSubject = subjectTxt.Text.Trim();

string mailFrom = fromTxt.Text.Trim();

string mailBody = bodytxt.Text.Trim();

//实例化MailAddress

MailAddress maddr = new MailAddress(mailFrom);//包含收件人地址的MailAddress

//初始化MailMessage

MailMessage mymail = new MailMessage();

mymail.To.Add(mailTo);//向收件人地址集合添加邮件地址

.Add(mailCC);//向抄送收件人地址集合添加邮件地址

mymail.From = mailFrom;//发件人地址

mymail.Subject = mailSubject;//邮件标题

mymail.SubjectEncoding = Encoding.UTF8;//获取或设置电子邮件的主题内容实用的编码

mymail.Body = mailBody;//邮件正文

mymail.BodyEncoding = Encoding.UTF8;//获取或设置邮件正文的编码

//设置优先级

switch (prptComBox.SelectedText.ToString())

{

case"高":

mymail.Priority = MailPriority.High;

break;

case"中":

mymail.Priority = MailPriority.Normal;

break;

case"低":

mymail.Priority = MailPriority.Low;

break;

default:

break;

}

//添加附件(Attachment 表示电子邮件的附件)

if (AttachTxt.Text != "")//有附件

{

Attachment item = new Attachment(AttachTxt.Text); mymail.Attachments.Add(item);

}

//以HTML格式还是纯文本发送

if (rBtnHTML.Checked == true)

{

//以HTML格式发送

mymail.IsBodyHtml = true;

}

else

{

//以纯文本格式发送

mymail.IsBodyHtml = false;

}

string mailPwd = SendMail.mailPwd;

SmtpClient smtp = new SmtpClient();//SmtpClient允许用户用来发送邮件的实例

smtp.Credentials = new

workCredential(mailFrom, mailPwd);//Credentials获取或设置用于发件人身份的凭据

smtp.Host = SendMail.mailServer;//设置SMTP邮件服务器

try

{

smtp.Send(mymail);

MessageBox.Show("发送成功!");

相关主题