一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

asp.net C#使用SMTP发送附件程序

时间:2013-11-18 编辑:简简单单 来源:一聚教程网

几年前有股学C#的热情,写下了C#发送邮件和C#发送带附件的邮件文章,放到baidu上。之前有有放到ttlsa上,但是搜索发现文章貌似被删除了,今天特意重新补充一下。此文留作记录.

以下代码除了实现发送简单的邮件以外,还包括了发送附件。From图没有贴出,上面就两按钮,一个“添加附件”、一个“发送”。点击添加附件选择文件, 文件路径全存储在listbox1中。在发送按钮方法中,把listbox1所有的文件添加到mailmessage对象里作为邮件发送出去了,请看代码

 代码如下 复制代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Net.Mime;

namespace SmtpTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
try
{
//定义一个mail对象
MailMessage mailmessage = new MailMessage(““, ““, “this is a test”, “yes!test!”);
//from email,to email,主题,邮件内容
mailmessage.Priority = MailPriority.Normal; //邮件优先级
SmtpClient smtpClient = new SmtpClient(“smtp.163.com”, 25); //smtp地址以及端口号
smtpClient.Credentials = new NetworkCredential(“ttlsa.com”, “xxxxxx”);//smtp用户名密码
smtpClient.EnableSsl = true; //启用ssl

//添加附件
Attachment attachment =null;
if(listBox1.Items.Count>0)
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
string pathFileName = listBox1.Items[i].ToString();
string extName = Path.GetExtension(pathFileName).ToLower(); //获取扩展名
if(extName==”.rar”||extName==”.zip”) //.rar和.zip的文件属于压缩文件类型
{
attachment = new Attachment(pathFileName,MediaTypeNames.Application.Zip);

}else
{
attachment = new Attachment(pathFileName,MediaTypeNames.Application.Octet);
}
//设置附件的MIME信息
ContentDisposition cd = attachment.ContentDisposition;
cd.CreationDate = File.GetCreationTime(pathFileName);//设置附件的创建时间
cd.ModificationDate = File.GetLastWriteTime(pathFileName);//设置附件的修改时间
cd.ReadDate = File.GetLastAccessTime(pathFileName);//设置附件的访问时间
mailmessage.Attachments.Add(attachment);//将附件添加到mailmessage对象
}
}
smtpClient.Send(mailmessage);
MessageBox.Show(“发送成功”);
}
catch (SmtpException se)
{
MessageBox.Show(se.StatusCode.ToString());
}
}

//添加附件,把文件添加到listbox中
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog opd = new OpenFileDialog();//定义一个选择文件的对话框
opd.Multiselect = true;//允许选择多个文件
opd.CheckFileExists = true;//检查文件是否存在
opd.ValidateNames = true;//检查文件名的可用性
opd.ShowDialog();//打开对话框
if(opd.FileNames.Length>0)//将选择的文件路径写入listbox中
{
listBox1.Items.AddRange(opd.FileNames);
}
}
}
}

热门栏目