用System.Net.Mail发送邮件

转自:http://blog.jailu.cn/2007/04/system_net_mail/


最近有不少朋友询问关于如何在.NET 2.0中发送邮件的问题,这里写一个简单的例子供朋友参考。

MSDN参考:
SmtpClient(http://msdn2.microsoft.com/zh-cn/library/system.net.mail.smtpclient(VS.80).aspx)
MailMessage(http://msdn2.microsoft.com/zh-cn/library/system.net.mail.mailmessage(VS.80).aspx)

下面是一段简单的发邮件代码(控制台程序):

using System;
using System.Collections.Generic;
using System.Text;

using System.Net.Mail;

namespace MailSender
{
    class Program
    {
        static string strHost = string.Empty;
        static string strAccount = string.Empty;
        static string strPwd = string.Empty;
        static string strFrom = string.Empty;

        static void Main(string[] args)
        {
            strHost = "smtp.163.com";   //STMP服务器地址
            strAccount = "****";       //SMTP服务帐号
            strPwd = "123456789";       //SMTP服务密码
            strFrom = "***@163.com";  //发送方邮件地址

            Console.WriteLine(sendMail("***@qq.com", "这是一封测试邮件", "这是一封测试邮件的正文内容") ? "Success" : "Unsuccess");

            Console.ReadLine();
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="to">接收方邮件地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="content">邮件正文内容</param>
        /// <returns></returns>
        /// <author>Jailu</author>
        /// <date>2007-04-10</date>
        static bool sendMail(string to, string title, string content)
        {
            SmtpClient _smtpClient = new SmtpClient();
            _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            _smtpClient.Host = strHost; ;//指定SMTP服务器
            _smtpClient.Credentials = new System.Net.NetworkCredential(strAccount, strPwd);//用户名和密码

            MailMessage _mailMessage = new MailMessage(strFrom,to);
            _mailMessage.Subject = title;//主题
            _mailMessage.Body = content;//内容
            _mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码
            _mailMessage.IsBodyHtml = true;//设置为HTML格式
            _mailMessage.Priority = MailPriority.High;//优先级

            try
            {
                _smtpClient.Send(_mailMessage);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}


你可能感兴趣的:(用System.Net.Mail发送邮件)