实例介绍
【实例简介】
发送邮件和短信
【实例截图】
【核心代码】
using LumiSoft.Net.SMTP.Client;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Push
{
class Program
{
static void Main(string[] args)
{
MailBodyEntity mailBodyEntity = new MailBodyEntity();
SendServerConfigurationEntity sendServerConfiguration = new SendServerConfigurationEntity();
Console.Write("发件人昵称:");
mailBodyEntity.Sender = Console.ReadLine();//wangs
Console.Write("发件人:");
mailBodyEntity.SenderAddress = sendServerConfiguration.SenderAccount = Console.ReadLine();//wangs@quickwide.com
sendServerConfiguration.SmtpHost = GetMailServer(mailBodyEntity.SenderAddress);
sendServerConfiguration.SmtpPort = 465;
Console.Write("发件人密码:");
sendServerConfiguration.SenderPassword = Console.ReadLine();//karimlmwxvnzcagi
Console.Write("收件人:");
mailBodyEntity.Recipients = new List<string> { Console.ReadLine() };//810273476@qq.com
Console.Write("主题:");
mailBodyEntity.Subject = Console.ReadLine();//测试
Console.Write("内容:");
mailBodyEntity.MailTextBody = Console.ReadLine();//测试内容
//string result = SendMail(sender, subject, body, reciplentList);
SendResultEntity sendResultEntity = MailKitSendMail(mailBodyEntity, sendServerConfiguration);
string result = mailBodyEntity.SenderAddress "发送" mailBodyEntity.MailTextBody "给" mailBodyEntity.Recipients[0] ",发送结果:" sendResultEntity.ResultInformation;
Console.WriteLine(result);
Console.ReadKey();
}
public static SendResultEntity MailKitSendMail(MailBodyEntity mailBodyEntity, SendServerConfigurationEntity sendServerConfiguration)
{
if (mailBodyEntity == null)
{
throw new ArgumentNullException();
}
if (sendServerConfiguration == null)
{
throw new ArgumentNullException();
}
SendResultEntity sendResultEntity = new SendResultEntity();
using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
Connection(mailBodyEntity, sendServerConfiguration, client, sendResultEntity);
if (sendResultEntity.ResultStatus == false)
{
return sendResultEntity;
}
SmtpClientBaseMessage(client);
Authenticate(mailBodyEntity, sendServerConfiguration, client, sendResultEntity);
if (sendResultEntity.ResultStatus == false)
{
return sendResultEntity;
}
Send(mailBodyEntity, sendServerConfiguration, client, sendResultEntity);
if (sendResultEntity.ResultStatus == false)
{
return sendResultEntity;
}
client.Disconnect(true);
}
return sendResultEntity;
}
/// <summary>
/// 连接服务器
/// </summary>
/// <param name="mailBodyEntity">邮件内容</param>
/// <param name="sendServerConfiguration">发送配置</param>
/// <param name="client">客户端对象</param>
/// <param name="sendResultEntity">发送结果</param>
public static void Connection(MailBodyEntity mailBodyEntity, SendServerConfigurationEntity sendServerConfiguration, MailKit.Net.Smtp.SmtpClient client, SendResultEntity sendResultEntity)
{
try
{
client.Connect(sendServerConfiguration.SmtpHost, sendServerConfiguration.SmtpPort);
}
catch (SmtpCommandException ex)
{
sendResultEntity.ResultInformation = $"尝试连接时出错:{0}" ex.Message;
sendResultEntity.ResultStatus = false;
}
catch (SmtpProtocolException ex)
{
sendResultEntity.ResultInformation = $"尝试连接时的协议错误:{0}" ex.Message;
sendResultEntity.ResultStatus = false;
}
catch (Exception ex)
{
sendResultEntity.ResultInformation = $"服务器连接错误:{0}" ex.Message;
sendResultEntity.ResultStatus = false;
}
}
/// <summary>
/// 账户认证
/// </summary>
/// <param name="mailBodyEntity">邮件内容</param>
/// <param name="sendServerConfiguration">发送配置</param>
/// <param name="client">客户端对象</param>
/// <param name="sendResultEntity">发送结果</param>
public static void Authenticate(MailBodyEntity mailBodyEntity, SendServerConfigurationEntity sendServerConfiguration, MailKit.Net.Smtp.SmtpClient client, SendResultEntity sendResultEntity)
{
try
{
client.Authenticate(sendServerConfiguration.SenderAccount, sendServerConfiguration.SenderPassword);
}
catch (AuthenticationException ex)
{
sendResultEntity.ResultInformation = $"无效的用户名或密码:{0}" ex.Message;
sendResultEntity.ResultStatus = false;
}
catch (SmtpCommandException ex)
{
sendResultEntity.ResultInformation = $"尝试验证错误:{0}" ex.Message;
sendResultEntity.ResultStatus = false;
}
catch (SmtpProtocolException ex)
{
sendResultEntity.ResultInformation = $"尝试验证时的协议错误:{0}" ex.Message;
sendResultEntity.ResultStatus = false;
}
catch (Exception ex)
{
sendResultEntity.ResultInformation = $"账户认证错误:{0}" ex.Message;
sendResultEntity.ResultStatus = false;
}
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="mailBodyEntity">邮件内容</param>
/// <param name="sendServerConfiguration">发送配置</param>
/// <param name="client">客户端对象</param>
/// <param name="sendResultEntity">发送结果</param>
public static void Send(MailBodyEntity mailBodyEntity, SendServerConfigurationEntity sendServerConfiguration, MailKit.Net.Smtp.SmtpClient client, SendResultEntity sendResultEntity)
{
try
{
client.Send(MailMessageHelper.AssemblyMailMessage(mailBodyEntity));
}
catch (SmtpCommandException ex)
{
switch (ex.ErrorCode)
{
case SmtpErrorCode.RecipientNotAccepted:
sendResultEntity.ResultInformation = $"收件人未被接受:{ex.Message}";
break;
case SmtpErrorCode.SenderNotAccepted:
sendResultEntity.ResultInformation = $"发件人未被接受:{ex.Message}";
break;
case SmtpErrorCode.MessageNotAccepted:
sendResultEntity.ResultInformation = $"消息未被接受:{ex.Message}";
break;
}
sendResultEntity.ResultStatus = false;
}
catch (SmtpProtocolException ex)
{
sendResultEntity.ResultInformation = $"发送消息时的协议错误:{ex.Message}";
sendResultEntity.ResultStatus = false;
}
catch (Exception ex)
{
sendResultEntity.ResultInformation = $"邮件接收失败:{ex.Message}";
sendResultEntity.ResultStatus = false;
}
}
/// <summary>
/// 获取SMTP基础信息
/// </summary>
/// <param name="client">客户端对象</param>
/// <returns></returns>
public static MailServerInformation SmtpClientBaseMessage(MailKit.Net.Smtp.SmtpClient client)
{
var mailServerInformation = new MailServerInformation
{
Authentication = client.Capabilities.HasFlag(SmtpCapabilities.Authentication),
BinaryMime = client.Capabilities.HasFlag(SmtpCapabilities.BinaryMime),
Dsn = client.Capabilities.HasFlag(SmtpCapabilities.Dsn),
EightBitMime = client.Capabilities.HasFlag(SmtpCapabilities.EightBitMime),
Size = client.MaxSize
};
return mailServerInformation;
}
/// <summary>
/// 创建邮件日志文件
/// </summary>
/// <returns></returns>
public static string CreateMailLog()
{
var logPath = AppDomain.CurrentDomain.BaseDirectory "/DocumentLog/"
Guid.NewGuid() ".txt";
if (File.Exists(logPath)) return logPath;
var fs = File.Create(logPath);
fs.Close();
return logPath;
}
public static string JmailSendMail(string sender, string subject, string body, List<string> reciplentList)
{
string result = "";
string reciplentStr = "";
//Message message = new Message();
////开启日志功能
//message.Logging = true;
////设置发送者
//message.From = sender;
//foreach (string reciplent in reciplentList)
//{
// message.AddRecipient(reciplent);
// reciplentStr = reciplent;
//}
////添加主题
//message.Subject = subject;
////添加正文
//message.Body = body;//message.AppendText = body;
//string mailServer = GetMailServer(sender);
//message.Send("smtp." mailServer, false);
return sender "发送" body "给" reciplentStr ",发送" result;
}
public static string SendMail(string sender, string subject, string body, List<string> reciplentList)
{
string result = "";
string reciplentStr = "";
//指定要附加和发送的文件。
string filePath = "";
MailMessage mailMessage = new MailMessage();
SetSenderAndRicplent(sender, reciplentList, mailMessage);
SetAttachment(filePath, mailMessage);
SetBody(subject, body, mailMessage);
string host = GetLocalIP();
//发送消息。
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(host);
//如果SMTP服务器需要,请添加凭据。
//如果服务器需要客户端,则需要凭据
client.Credentials = CredentialCache.DefaultNetworkCredentials;
//在代表客户发送电子邮件之前进行身份验证。
client.UseDefaultCredentials = true;
try
{
client.Send(mailMessage);
foreach (string reciplent in reciplentList)
{
reciplentStr = reciplent;
}
}
catch (Exception e)
{
throw e;
}
finally
{
client.Dispose();
}
return sender "发送" body "给" reciplentList ",发送" result;
}
/// <summary>
/// 设置邮箱正文
/// </summary>
/// <param name="subject"></param>
/// <param name="content"></param>
/// <param name="mailMessage"></param>
private static void SetBody(string subject, string body, MailMessage mailMessage)
{
if (!string.IsNullOrEmpty(subject) && !string.IsNullOrEmpty(body))
{
//设置邮件主题
mailMessage.Subject = subject;
//设置邮件内容
mailMessage.Body = body;
mailMessage.Body = body;
}
}
/// <summary>
/// 创建邮件并设置发件人和收件人
/// </summary>
/// <param name="sender"></param>
/// <param name="reciplentList"></param>
/// <param name="mailMessage"></param>
private static void SetSenderAndRicplent(string sender, List<string> reciplentList, MailMessage mailMessage)
{
MailAddress fromAddress = new MailAddress(sender);
mailMessage.From = fromAddress;
foreach (string reciplent in reciplentList)
{
mailMessage.To.Add(reciplent);
}
}
/// <summary>
/// 添加附件
/// </summary>
/// <param name="filePath"></param>
/// <param name="mailMessage"></param>
private static void SetAttachment(string filePath, MailMessage mailMessage)
{
if (!string.IsNullOrEmpty(filePath) && !File.Exists(filePath))
{
//为此电子邮件创建文件附件。
System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(filePath, MediaTypeNames.Application.Octet);
//为文件提交时间戳
System.Net.Mime.ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(filePath);
disposition.ModificationDate = File.GetLastWriteTime(filePath);
disposition.ReadDate = File.GetLastAccessTime(filePath);
//将文件附件添加到此电子邮件中。
mailMessage.Attachments.Add(data);
}
}
/// <summary>
/// 获取主机IP
/// </summary>
/// <returns></returns>
private static string GetLocalIP()
{
string ip = "";
try
{
string hostName = Dns.GetHostName();//得到主机名
IPHostEntry ipEntry = Dns.GetHostEntry(hostName);//Dns.GetHostEntryAsync(hostName)
foreach (IPAddress iPAddress in ipEntry.AddressList)
{
//从IP地址列表中筛选出IPv4类型的IP地址
//AddressFamily.InterNetwork表示此IP为IPv4,
//AddressFamily.InterNetworkV6表示此地址为IPv6类型
if (iPAddress.AddressFamily==AddressFamily.InterNetwork)
{
ip = iPAddress.ToString();
}
}
}
catch (Exception e)
{
throw e;
}
return ip;
}
/// <summary>
/// 获取邮箱服务器
/// </summary>
/// <param name="sender"></param>
/// <returns></returns>
private static string GetMailServer(string sender)
{
int index = sender.IndexOf("@");
string mailServer = "smtp." sender.Substring(index 1);
return mailServer;
}
}
}
标签: 推送
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论