C#学习过程中,偶然间接触到邮件发送的标题,点进去看看,收获不小。就试着自己写了一个,成功的发到邮箱里了。先上图:简单的界面设计
代码如下:
using System.Windows.Forms;using System;namespace SMTPTEST{public partial class Form1 : Form{public Form1(){InitializeComponent();}/// <summary>/// 浏览上传文件/// </summary>/// <param name=\"sender\"></param>/// <param name=\"e\"></param>private void FS_FILE_button_Click(object sender, System.EventArgs e){//设置对话框的初始目录为C盘this.openFileDialog1.InitialDirectory = \"C:\\\\\";//筛选字符串为所有文件this.openFileDialog1.Filter = \"所有文件(*.*)|*.*\";this.openFileDialog1.RestoreDirectory = true;if (this.openFileDialog1.ShowDialog() == DialogResult.OK){string PicFileName = this.openFileDialog1.FileName.Trim();// 当选择好文件后将文件名赋值给下拉框this.FS_FILE_comboBox.Items.Add(PicFileName);}}/// <summary>/// 取消按钮/// </summary>/// <param name=\"sender\"></param>/// <param name=\"e\"></param>private void QX_button_Click(object sender, System.EventArgs e){Application.Exit();}private void FS_SEND_button_Click(object sender, System.EventArgs e){try{//SmtpClient下的一个对象,用以设置邮件的主题和内容System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage();//发送端到接收端的邮箱地址myMail = new System.Net.Mail.MailMessage( this.FSEMAIL_URL_textBox.Text.Trim(), this.RVEMAIL_URL_textBox.Text.Trim());myMail.Subject = this.FS_TITLE_textBox.Text.Trim();myMail.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码myMail.Body = this.FS_TEXT_textBox.Text.Trim();myMail.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码//myMail.From = new System.Net.Mail.MailAddress();if (FS_FILE_comboBox.Items.Count > 0){for (int i = 0; i < FS_FILE_comboBox.Items.Count; i++){ //建立邮件附件类的一个对象,语法格式为System.Net.Mail.Attachment(文件名,文件格式)System.Net.Mail.Attachment myAttachment = new System.Net.Mail.Attachment(FS_FILE_comboBox.Items[i].ToString(), System.Net.Mime.MediaTypeNames.Application.Octet);//用smtpclient对象里attachments属性,添加上面设置好的myattachmentmyMail.Attachments.Add(myAttachment);}}//建立发送对象client,验证邮件服务器,服务器端口,用户名,以及密码System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(FSSERVICER_textBox.Text.Trim(), Convert.ToInt32(FSPOINT_textBox.Text.Trim()));client.UseDefaultCredentials = true;client.Credentials = new System.Net.NetworkCredential(FSEMAIL_URL_textBox.Text.Trim(), FSEMAIL_PWD_textBox.Text.Trim());client.Send(myMail);MessageBox.Show(\"邮件发送成功!\", \"提示\", MessageBoxButtons.OK, MessageBoxIcon.Information);}catch (Exception ex){MessageBox.Show(ex.Message, \"提示\", MessageBoxButtons.OK, MessageBoxIcon.Information);}}/// <summary>/// 鼠标点击发送服务器文本框中,依据发送邮箱地址为发送服务器赋值/// </summary>/// <param name=\"sender\"></param>/// <param name=\"e\"></param>private void FS_SERVICER_MouseDown(object sender, MouseEventArgs e){string send_email_url = this.FSEMAIL_URL_textBox.Text.Trim();if(send_email_url != null && !\"\".Equals(send_email_url )){string[] vs = send_email_url.Split(\'@\');this.FSSERVICER_textBox.Text = \"smtp.\" + vs[vs.Length - 1];}}}}
关于发送时报错:不允许使用邮箱名称。。。
现在的一些邮箱都设置了SMTP发送邮件需要客户端授权密码,将邮箱的授权密码写在邮箱密码字段上就可以了。