发送邮件

      在.NET框架提供用于处理电子邮件时, System.Net.Mail命名空间的整个空间。在下面的例子中,将使用这个命名空间两类: MailMessage类,实际的电子邮件和SmtpClient类,用于发送电子邮件。

   

public static bool SendMail(string Email, string MailSubject, string MailBody)
    {
        bool isSent = false, isMailVIASSL = Convert.ToBoolean(ConfigurationManager.AppSettings["MailServerUseSsl"]);

        string mailHost = ConfigurationManager.AppSettings["MailServerAddress"].ToString(),
        senderAddress = ConfigurationManager.AppSettings["MailServerSenderUserName"].ToString(),
        senderPassword = ConfigurationManager.AppSettings["MailServerSenderPassword"].ToString();

        int serverPort = Convert.ToInt32(ConfigurationManager.AppSettings["MailServerPort"]);

        MailMessage msgEmail = new MailMessage(new MailAddress(senderAddress), new MailAddress(Email));
        using (msgEmail)
        {
            msgEmail.IsBodyHtml = true;
            msgEmail.BodyEncoding = System.Text.Encoding.UTF8;
            msgEmail.Subject = MailSubject;
            msgEmail.Body = MailBody;

            using (SmtpClient smtp = new SmtpClient(mailHost))
            {
                smtp.UseDefaultCredentials = false;
                smtp.EnableSsl = isMailVIASSL;
                smtp.Credentials = new NetworkCredential(senderAddress, senderPassword);
                smtp.Port = serverPort;
                try
                {
                    smtp.Send(msgEmail);
                    isSent = true;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        return isSent;
    }

<!-- Mail Server Settings -->
<add key="MailServerAddress" value="smtp.gmail.com" />
<add key="MailServerPort" value="25" />
<add key="MailServerSenderUserName" value="[email protected]" />
<add key="MailServerSenderPassword" value="password" />
<add key="MailServerUseSsl" value="True" />

 

你可能感兴趣的:(发送邮件)