发送类
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Emeil
{
public class SendReceiveEmail
{
#region ///属性声明
private string _from; //发件邮箱
private string[] _to; //收件邮箱列表
private string _subject; //主题
private string _body; //正文
private string[] _filepath; //附件列表
private string _usename; //登录邮箱账号
private string _password; //密码
private string _smtp; //服务器
private int _port; //端口号
public string From
{ get { return _from; } set { _from = value; } }
public string[] To
{ get { return _to; } set { _to = value; } }
public string Subject
{ get { return _subject; } set { _subject = value; } }
public string Body
{ get { return _body; } set { _body = value; } }
public string[] Filepath
{ get { return _filepath; } set { _filepath = value; } }
public string Usename
{ get { return _usename; } set { _usename = value; } }
public string Password
{ get { return _password; } set { _password = value; } }
public string Smtp
{ get { return _smtp; } set { _smtp = value; } }
public int Port
{ get { return _port; } set { _port = value; } }
#endregion
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="from 发件邮箱"></param>
/// <param name="to 收件邮箱"></param>
/// <param name="subject 主题"></param>
/// <param name="body 正文"></param>
/// <param name="attachmentpath 附件"></param>
/// <returns></returns>
public bool SendEmail()
{
try
{
//定义一个mail对象
MailMessage mailmessage = new MailMessage();
//发信人地址
mailmessage.From= new MailAddress(_from);
//添加收件人
for (int t = 0; t < _to.Length; t++)
{
mailmessage.To.Add(new MailAddress(_to[t]));
}
//主题
mailmessage.Subject = _subject;
//正文
mailmessage.Body = _body;
//邮件优先级
mailmessage.Priority = MailPriority.Normal;
//添加附件
Attachment attachment = null;
//添加所有附件
if (_filepath.Length > 0)
{
for (int i = 0; i < _filepath.Length; i++)
{
string pathFileName = _filepath[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对象
}
}