C#.NET发送邮件的实例代码
程序员文章站
2024-03-01 18:06:46
复制代码 代码如下:using system;using system.collections.generic;using system.text;using system...
复制代码 代码如下:
using system;
using system.collections.generic;
using system.text;
using system.net.mail;
using system.net;
namespace myquery.utils
{
/// <summary>
/// 封装邮件处理
/// by 贾世义 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>
/// 设置发送邮件参数
/// </summary>
/// <param name="host">smtp服务器地址或名称</param>
/// <param name="port">smtp服务端口 一般为25</param>
/// <param name="isusercredentials">是否需要认证</param>
/// <param name="account">需要认证时的用户</param>
/// <param name="password">需要认证时的用户的密码</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>
/// 设置发送邮件参数 取配置
/// </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>
/// 发送邮件 发送邮件错误不会抛出异常
/// </summary>
/// <param name="receivers">收件人</param>
/// <param name="title">标题/主题</param>
/// <param name="content">信件内容</param>
/// <param name="sender">发件人 空则取系统配置</param>
public static void sendmail(string receivers, string title, string content, string sender)
{
if (!string.isnullorempty(receivers))
{
//初始化参数
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 { }
}
}
}
}
}