代码改变世界

c# smtp发送邮件

2010-03-24 08:45  zhangbaoyu  阅读(345)  评论(0编辑  收藏  举报

public static string SendSMTPEMail(Model.ModelMail_Management modelmail)
{
    System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(modelmail.MailSenderFrom, modelmail.MailSenderFrom);

 

    System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(modelmail.MailSenderTo, modelmail.MailSenderTo);

    System.Net.Mail.MailMessage oMail = new System.Net.Mail.MailMessage(from, to);

    oMail.Subject = modelmail.MailSubject;
    oMail.Body = modelmail.MailBody;

    oMail.IsBodyHtml = true;
    oMail.BodyEncoding = System.Text.Encoding.UTF8;

    //Attachment attachFile = new Attachment("d:\\myinfo.rar");
    //oMail.Attachments.Add(attachFile);

    oMail.Priority = System.Net.Mail.MailPriority.Normal;

    System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);

    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
    client.Host = modelmail.MailSenderAddress;

    client.Port = Convert.ToInt32(modelmail.MailSenderPort);
    client.Timeout = 100000;
    client.ServicePoint.MaxIdleTime = 1;

    client.UseDefaultCredentials = false;
    client.Credentials = new System.Net.NetworkCredential(modelmail.MailSenderFrom, modelmail.MailSenderPassport);
    client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;


    try
    {
        client.Send(oMail);
        return "OK";
    }

    catch (System.Net.Mail.SmtpException ex)
    {
        return ex.Message.ToString();
    }
    finally
    {
        oMail.Dispose();
    }
}