5人参与 • 2025-03-07 • Asp.net
在c#编程环境中,实现邮件发送功能是一项常见的需求,无论是web应用程序还是windows窗体应用程序,邮件服务都能帮助用户进行信息的传递和沟通。使用c#中的system.net库,来实现自动发送邮件的功能。
下面进行邮箱的授权,本篇文章使用qq邮箱作为案列进行示范。



发送完成按照指引将会获得一串授权码。将授权码填入下面代码的指定位置。
使用system.net.mail发送一封简单的文本邮件:
using system;
using system.net;
using system.net.mail;
class emailsender
{
public static void main()
{
try
{
// 配置smtp服务器信息(以qq邮箱为例)
string smtpserver = "smtp.qq.com"; //此处修改发送邮箱的服务器地址
int smtpport = 587;
bool enablessl = true;
string fromemail = "your_email@qq.com";//使用的邮箱
string password = "your_password_or_auth_code"; // 此处填写刚刚获得的授权码
// 创建邮件客户端
using smtpclient client = new smtpclient(smtpserver)
{
port = smtpport,
credentials = new networkcredential(fromemail, password),
enablessl = enablessl
};
// 创建邮件内容
mailmessage message = new mailmessage
{
from = new mailaddress(fromemail),
subject = "测试邮件",
body = "这是一封来自c#程序的测试邮件",
isbodyhtml = false // 设置为true发送html邮件
};
// 添加收件人
message.to.add("recipient@example.com"); //填入接受邮件的邮箱地址
// 发送邮件
client.send(message);
console.writeline("邮件发送成功!");
}
catch (exception ex)
{
console.writeline($"邮件发送失败:{ex.message}");
}
}
}常见邮箱服务器配置
| 邮箱服务商 | smtp服务器地址 | 端口 | ssl要求 |
|---|---|---|---|
| qq邮箱 | smtp.qq.com | 587 | 是 |
| 163邮箱 | smtp.163.com | 465 | 是 |
| gmail | smtp.gmail.com | 587 | 是 |
| outlook | smtp.office365.com | 587 | 是 |
制作一个报错提醒功能的函数,当现成的程序出现了问题,自动发送邮件提醒程序员进行远程处理。打工的牛马制作一个鞭子抽自己起来干活。实现效果如下

using system;
using system.diagnostics;
using system.net;
using system.net.mail;
using system.security.cryptography;
using system.text;
class emailsender
{
// ======== 配置信息 ========
static string smtpserver = "smtp.qq.com";
static int smtpport = 587;
static bool enablessl = true;
static string fromemail = "填入发送的邮箱"; //发送邮箱
static string password = "邮箱授权码"; // qq邮箱需要授权码
static string incomingemail = "接受邮件的邮箱地址";//收件邮箱地址
private static readonly object filelock = new object();
private const string logdirectory = "emailsendlogs";
/// <summary>
/// 报警信息发送至邮箱
/// </summary>
/// <param name="alertlevel">报警级别支持:
/// critical:严重问题(红色)
/// high:高级别问题(橙色)
/// medium:中等问题(黄色)
/// low:低级别通知(绿色)
/// </param>
/// <param name="alertcontent">报警内容</param>
/// <param name="errordetails">错误详情</param>
/// <param name="attachmentpaths">附件</param>
public static void sendtoemail(string alertlevel, string alertcontent, string errordetails = null, string[] attachmentpaths = null)
{
try
{
//1和2是会在程序运行的文件夹中生成一个日志文件,当同一个报错今天已经发送过了,将会 //不再发送,防止报错一直触发然后一直给自己发送邮件,这样子抽牛马干活打在自己身上就太痛了
// ===== 1. 生成错误唯一标识 =====
string errorhash = generateerrorhash(alertcontent, errordetails);
// ===== 2. 检查是否已发送过 =====
if (isalreadysenttoday(errorhash))
{
console.writeline("相同错误今日已发送过,不再重复发送");
return;
}
// ======== 创建邮件客户端 ========
using smtpclient client = new smtpclient(smtpserver)
{
port = smtpport,
credentials = new networkcredential(fromemail, password),
enablessl = enablessl
};
// ======== 报警级别颜色映射 ========
var alertlevelinfo = new dictionary<string, (string color, string emoji)>
{
{ "critical", ("#d32f2f", "🔥") }, // 红色
{ "high", ("#f57c00", "⚠️") }, // 橙色
{ "medium", ("#ffa000", "❗") }, // 黄色
{ "low", ("#4caf50", "ℹ️") } // 绿色
};
// 获取当前报警级别的颜色和表情符号
var (color, emoji) = alertlevelinfo.containskey(alertlevel)
? alertlevelinfo[alertlevel]
: ("#666666", "🔔");
// ======== 构建邮件内容 ========
string htmlbody = $@"
<!doctype html>
<html>
<head>
<style>
.card {{
border: 1px solid #e0e0e0;
padding: 20px;
max-width: 800px;
font-family: 'segoe ui', tahoma, geneva, verdana, sans-serif;
}}
.header {{
border-bottom: 2px solid {color};
padding-bottom: 10px;
margin-bottom: 20px;
}}
.alert-level {{
color: {color};
font-weight: bold;
}}
pre {{
background: #f8f9fa;
padding: 15px;
border-radius: 4px;
overflow-x: auto;
}}
</style>
</head>
<body>
<div class='card'>
<div class='header'>
<h2>{emoji} 系统报警 - {alertlevel}</h2>
</div>
<table>
<tr><th>报警时间:</th><td>{datetime.now:yyyy-mm-dd hh:mm:ss}</td></tr>
<tr><th>报警级别:</th><td class='alert-level'>{alertlevel}</td></tr>
</table>
<h3>▌ 报警内容</h3>
<p>{alertcontent}</p>
{(errordetails != null ? $@"
<h3>▌ 错误详情</h3>
<pre>{errordetails}</pre>
" : "")}
<div style='margin-top: 25px; color: #666; font-size: 0.9em;'>
<hr>
<p>此邮件由系统自动发送,请勿直接回复</p>
<p>负责人:牛马程序员 (123456@niuma.com)</p>
</div>
</div>
</body>
</html>";
// ======== 创建邮件消息 ========
mailmessage message = new mailmessage
{
from = new mailaddress(fromemail),
subject = $"{emoji} 系统报警 - {alertlevel}",
body = htmlbody,
isbodyhtml = true
};
// 添加收件人
message.to.add(incomingemail);
// 添加附件
if (attachmentpaths != null)
{
foreach (var path in attachmentpaths)
{
if (file.exists(path))
{
message.attachments.add(new attachment(path));
}
}
}
// ======== 发送邮件 ========
client.send(message);
// ===== 4. 记录发送日志 =====
logerror(errorhash, alertlevel, alertcontent, errordetails);
console.writeline("邮件发送成功!");
}
catch (exception ex)
{
console.writeline($"邮件发送失败:{ex.message}");
}
}
/// <summary>
/// 创建唯一加密标识符号
/// </summary>
/// <param name="content"></param>
/// <param name="details"></param>
/// <returns></returns>
private static string generateerrorhash(string content, string details)
{
using md5 md5 = md5.create();
string rawdata = $"{content}|{details}";
byte[] hashbytes = md5.computehash(encoding.utf8.getbytes(rawdata));
return bitconverter.tostring(hashbytes).replace("-", "");
}
/// <summary>
/// 检查是否已经发送过
/// </summary>
/// <param name="errorhash"></param>
/// <returns></returns>
private static bool isalreadysenttoday(string errorhash)
{
string todaylogfile = gettodaylogfilepath();
lock (filelock)
{
if (!file.exists(todaylogfile)) return false;
foreach (string line in file.readalllines(todaylogfile))
{
if (line.startswith(errorhash))
{
return true;
}
}
}
return false;
}
//记录报警内容
private static void logerror(string errorhash, string level,
string content, string details)
{
string logentry = $"{errorhash}|{datetime.now:yyyy-mm-dd hh:mm:ss}|" +
$"{level}|{content}|{details}\n";
lock (filelock)
{
ensurelogdirectoryexists();
file.appendalltext(gettodaylogfilepath(), logentry);
}
}
//获取报警日志地址
private static string gettodaylogfilepath()
{
return path.combine(logdirectory,
$"snederrorlog_{datetime.now:yyyymmdd}.txt");
}
//无文件创建文件夹
private static void ensurelogdirectoryexists()
{
if (!directory.exists(logdirectory))
{
directory.createdirectory(logdirectory);
}
}
public static void main()
{
sendtoemail(
alertlevel: "high",
alertcontent: "数据库益处请处理,可能导致系统响应缓慢。",
errordetails: "timeoutexception: could not connect to database.\n at databaseservice.connect() line 123",
attachmentpaths: new[] { "error.log" });
sendtoemail(
alertlevel: "high",
alertcontent: "数据库连接池使用率超过90%,可能导致系统响应缓慢。",
errordetails: "timeoutexception: could not connect to database.\n at databaseservice.connect() line 123",
attachmentpaths: new[] { "error.log" });
}
}到此这篇关于c#使用system.net库实现自动发送邮件功能的文章就介绍到这了,更多相关c#自动发送邮件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论