using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
namespace MyQuery.Utils
{
/// <summary>
/// Package mail processing
/// by Jia Shiyi 2011-6-3
/// </summary>
public static class MailHelper
{
private static string smtpHost = null;
private static int smptPort = 25;
private static bool smtpIsUserCredentials = false;
private static string smtpCredentialAccount = null;
private static string smtpCredentialPassword = null;
/// <summary>
/// Set the send message parameters
/// </summary>
/// <param name="host">smtp Server address or name </param>
/// <param name="port">smtp Service port 1 As for the 25</param>
/// <param name="isUserCredentials"> Whether certification is required </param>
/// <param name="account"> Users who need to be authenticated </param>
/// <param name="password"> The password of the user when authentication is required </param>
public static void SetParameters(string host, int port, bool isUserCredentials, string account, string password)
{
smtpHost = host;
smptPort = port;
smtpIsUserCredentials = isUserCredentials;
smtpCredentialAccount = account;
smtpCredentialPassword = password;
}
/// <summary>
/// Set the send message parameters Take the configuration
/// </summary>
private static void setParameters()
{
if (String.IsNullOrEmpty(smtpHost))
{
smtpHost = WebHelper.GetAppConfig("SmtpHost");
smptPort = DataHelper.GetIntValue(WebHelper.GetAppConfig("SmptPort"), 25);
smtpIsUserCredentials = Constants.TRUE_ID.Equals(WebHelper.GetAppConfig("SmtpIsUserCredentials"));
smtpCredentialAccount = WebHelper.GetAppConfig("SmtpCredentialAccount");
smtpCredentialPassword = WebHelper.GetAppConfig("SmtpCredentialPassword");
}
}
/// <summary>
/// Send E-mail Sending a message error does not throw an exception
/// </summary>
/// <param name="receivers"> The recipient </param>
/// <param name="title"> The title / The theme </param>
/// <param name="content"> letter </param>
/// <param name="sender"> The sender If null, take the system configuration </param>
public static void SendMail(string receivers, string title, string content, string sender)
{
if (!String.IsNullOrEmpty(receivers))
{
// Initialization parameter
setParameters();
if (!String.IsNullOrEmpty(smtpHost))
{
try
{
SmtpClient smtp = new SmtpClient(smtpHost, smptPort);
if (smtpIsUserCredentials)
{
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(smtpCredentialAccount, smtpCredentialPassword); ;
}
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
if (String.IsNullOrEmpty(sender))
{
sender = smtpCredentialAccount;
}
foreach (string receiver in DataHelper.GetStrings(receivers))
{
MailMessage msg = new MailMessage(sender, receiver, title, content);
msg.BodyEncoding = Encoding.UTF8;
msg.SubjectEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;
smtp.Send(msg);
msg.Dispose();
}
}
catch { }
}
}
}
}
}