using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppNetworkTestAndToEmail
{
internal enum ServerType
{
SERVER_163_COM,
SERVER_qq_COM,
}
internal class SendEmailTool
{
const string path = "";
internal static void TestSmtpClient(string mailFrom, string mailTo, string title, string content, string mailFromAccount, string mailPassword, ServerType serverType)
{
MailMessage mymail = new MailMessage();
mymail.From = new System.Net.Mail.MailAddress(mailFrom);
mymail.To.Add(mailTo);
mymail.Subject = title;
mymail.Body = content;
mymail.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient();
smtpclient.Timeout = 8000;
smtpclient.UseDefaultCredentials = false;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
if (serverType == ServerType.SERVER_163_COM)
{
smtpclient.Port = 25;
smtpclient.Host = "smtp.163.com";
}
else
{
smtpclient.Port = 587;
smtpclient.Host = "smtp.qq.com";
}
smtpclient.EnableSsl = true;
smtpclient.Credentials = new System.Net.NetworkCredential(mailFromAccount, mailPassword);
try
{
smtpclient.Send(mymail);
LogHelpter.AddLog($"发送成功,接收人{mailTo},标题={title},内容={content}");
}
catch (Exception ex)
{
LogHelpter.AddLog($"发送邮件失败.请检查.接收人{mailTo},标题={title},内容={content}" + ex.Message, null, "emailError");
}
}
}
}
LogHelpter
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppNetworkTestAndToEmail
{
public class LogHelpter
{
const int MAX_FILE_COUNT = 22;
static string fileSaveDir = "";
const long fileBytes = 258000;
private readonly static object lockObj = new object();
static LogHelpter()
{
Task.Run(() =>
{
while (true)
{
try
{
string[] filePathArr = System.IO.Directory.GetFileSystemEntries(fileSaveDir);
if (filePathArr == null || filePathArr.Length == 0)
{
goto DO_SELEEP;
}
List<FileInfo> files = new List<FileInfo>();
foreach (var item in filePathArr)
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(item);
files.Add(fileInfo);
}
var del_files = files.OrderByDescending(g => g.LastWriteTime).Skip(MAX_FILE_COUNT);
if (del_files == null || del_files.Count() == 0)
{
goto DO_SELEEP;
}
foreach (var file in del_files)
{
file.Delete();
}
}
catch (Exception ex)
{
Console.WriteLine("LogHelpter执行删除文件功能异常," + ex.Message);
}
DO_SELEEP:
System.Threading.Thread.Sleep(20000);
}
});
}
static string GetNewFileName(string fileFolderPath, string fileNameNoExtension, string fileNamePrefix = null)
{
string fileName = string.Empty;
fileNamePrefix = string.IsNullOrWhiteSpace(fileNamePrefix) ? "" : fileNamePrefix;
int index = 1;
if (fileNameNoExtension.LastIndexOf('_') == -1)
{
}
else
{
var arr = fileNameNoExtension.Split('_');
int.TryParse(arr[arr.Length - 1], out index);
if (index == 0 || index > 900)
{
index = 1;
}
}
fileName = Path.Combine(fileFolderPath, fileNamePrefix + DateTime.Now.ToString("yyyy-MM-dd") + "_" + index + ".log");
while (File.Exists(fileName))
{
if (File.ReadAllBytes(fileName).Length < fileBytes)
{
break;
}
index++;
fileName = Path.Combine(fileFolderPath, fileNamePrefix + DateTime.Now.ToString("yyyy-MM-dd") + "_" + index + ".log");
}
return fileName;
}
const string saveFolder = "log";
public static void AddLog(string msg, string storeDir = null, string fileNamePrefix = null)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "> " + msg);
lock (lockObj)
{
try
{
fileNamePrefix = string.IsNullOrWhiteSpace(fileNamePrefix) ? "" : fileNamePrefix + "_";
string fileFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, saveFolder);
if (!string.IsNullOrWhiteSpace(storeDir))
{
fileFolderPath = Path.Combine(fileFolderPath, storeDir);
}
if (Directory.Exists(fileFolderPath) == false)
{
Directory.CreateDirectory(fileFolderPath);
}
fileSaveDir = fileFolderPath;
string fileName = string.Empty;
string[] files = Directory.GetFiles(fileFolderPath);
if (files.Length == 0)
{
fileName = Path.Combine(fileFolderPath, fileNamePrefix + DateTime.Now.ToString("yyyy-MM-dd") + "_1.log");
goto DO_WRITE;
}
string[] files2 = files.OrderByDescending(x => int.Parse(x.Substring(x.LastIndexOf("_")).Split("_")[1].Split(".")[0])).ToArray();
FileInfo fileInfo = new FileInfo(files2[0]);
string fileNameNoExtension = Path.GetFileNameWithoutExtension(fileInfo.Name);
fileName = GetNewFileName(fileFolderPath, fileNameNoExtension, fileNamePrefix);
DO_WRITE:
FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write);
string msg2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ">" + msg + System.Environment.NewLine;
byte[] logBytes = UTF8Encoding.UTF8.GetBytes(msg2);
fs.Write(logBytes, 0, logBytes.Length);
fs.Flush();
fs.Close();
fs.Dispose();
}
catch (Exception ex)
{
Console.WriteLine("LogHelpter日志写入异常:" + ex.ToString());
}
}
}
}
}
调用参考
string mailFrom = "1122222@163.com";
string mailTo = "3333333@163.com";
string mailAccount = "555555@163.com";
string password = "16113333mailqx";
string title = "测试发送标题";
string content = "测试发送内容" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
SendEmailTool.TestSmtpClient(mailFrom, mailTo, title, content, mailAccount, password,ServerType.SERVER_163_COM);