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);
}
}
}
}
|