您的位置:首页 > 编程语言 > C#

c# 发送邮件代码,带附件

2013-03-28 09:00 337 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Diagnostics;

namespace Test28
{
class Program
{
static void Main(string[] args)
{
Email email = new Email()
{
fromEmail = "发送人邮箱",
fromPerson = "发件人",
toEmail = "接收人邮箱",
toPerson = "接收人",
encoding = "UTF-8",
smtpServer = "选用的邮件服务器平【比如:mail.163.com】",
userName = "你邮箱的用户名【比如:xxxxx@163.com】",
passWord = "你的邮箱的密码",
emailTitle = "邮件标题",
emailContent = "邮件内容"
};
SendEmail(email);
}

#region 邮件发送代码
/// <summary>
/// 邮件发送代码
/// </summary>
/// <param name="email"></param>
public static void SendEmail(Email email)
{
//try
//{
//设置发件人信箱,及显示名字
MailAddress from = new MailAddress(email.fromEmail, email.fromPerson);
//设置收件人信箱,及显示名字
MailAddress to = new MailAddress(email.toEmail, email.toPerson);
//创建一个MailMessage对象
MailMessage oMail = new MailMessage(from, to);
oMail.Subject = email.emailTitle; //邮件标题
oMail.Body = email.emailContent; //邮件内容
oMail.IsBodyHtml = true; //指定邮件格式,支持HTML格式
System.Net.Mail.Attachment mailAttach_1 = new   Attachment(@"c:\UserCenterLog.txt");//附件
oMail.Attachments.Add(mailAttach_1);
oMail.BodyEncoding = System.Text.Encoding.GetEncoding(email.encoding);//邮件采用的编码
oMail.Priority = MailPriority.High;//设置邮件的优先级为高
//发送邮件服务器
SmtpClient client = new SmtpClient();
client.Host = email.smtpServer; //指定邮件服务器
client.Credentials = new NetworkCredential(email.userName, email.passWord);//指定服务器邮件,及密码
//发送
client.Send(oMail); //发送邮件
oMail.Dispose(); //释放资源
//}
//catch(Exception ex)
//{
//    StreamWriter writer = File.AppendText(@"c:\00.txt");
//    writer.WriteLine(ex.Message);
//    writer.Close();
//    writer.Dispose();
//}
//finally
//{

//}
}
#endregion
}

class Email
{
public string fromEmail { get; set; }
public string fromPerson { get; set; }
public string toEmail { get; set; }
public string toPerson { get; set; }
public string encoding { get; set; }
public string smtpServer { get; set; }
public string userName { get; set; }
public string passWord { get; set; }
public string emailTitle { get; set; }
public string emailContent { get; set; }
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: