邮件发送
2012-07-17 17:59 Carl Xing 阅读(209) 评论(0) 编辑 收藏 举报前台界面:
后台代码:(不同的邮件主机可能会需要端口号)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net.Mail; using System.Net; using System.Threading; namespace Mail { public partial class SendMail : Form { public SendMail() { InitializeComponent(); } string[] FileNames { get; set; } //发送邮件按钮 private void btnSend_Click(object sender, EventArgs e) { string to = tbTo.Text; string from = "xxx@sina.com"; string subject = tbTheme.Text; string content = @tbContent.Text; MailMessage msg = new MailMessage(from, to, subject, content); msg.IsBodyHtml = true; //Thread threadMail = new Thread(new ParameterizedThreadStart(SendEmail)); //threadMail.Start(msg); ThreadPool.SetMaxThreads(0, 0); ThreadPool.QueueUserWorkItem(new WaitCallback(SendEmail), msg); btnSend.Enabled = false; } /// <summary> /// 异步发邮件 /// </summary> /// <param name="message"></param> private void SendEmail(object message) { SmtpClient client = new SmtpClient("smtp.sina.com");//有可能需要端口号 client.Credentials = new NetworkCredential("xxx@sina.com", "***"); MailMessage msg = message as MailMessage; if (FileNames != null) { foreach (string fileName in FileNames) { Attachment atta = new Attachment(fileName); msg.Attachments.Add(atta); } } client.Send(msg); this.Invoke(new ButtonEnableDelegate(EnableControl), new object[] { btnSend }); //Thread.CurrentThread.Abort(); } delegate void ButtonEnableDelegate(Control control); private void EnableControl(Control control) { control.Enabled = true; } //选择附件 private void btnAttach_Click(object sender, EventArgs e) { OpenFileDialog dia = new OpenFileDialog(); dia.Filter = "JPEG (*.jpg)|*.jpg|PNG (*.png)|*.png"; dia.RestoreDirectory = true; dia.Multiselect = true; if (dia.ShowDialog() == DialogResult.OK) { if (dia.FileNames.Length == 0) { return; } this.FileNames = dia.FileNames; this.tbAttach.Text = string.Empty; foreach (string fileName in dia.FileNames) { tbAttach.Text += fileName.Substring(fileName.LastIndexOf('\\')+1) + ";"; } } } } }