/// <summary> /// 发送邮件 正常情况下应该使用 MQ 来解耦发送邮件 -- 后面改为MQ /// </summary> /// <param name="title">邮件主题</param> /// <param name="htmlContent">邮件内容</param> /// <param name="emailTo">收件人邮箱 可以用分号分隔 发送到多个</param> /// <param name="emailToName">收件人姓名</param> /// <returns></returns> public async Task <string> SendSystemMailAsync(string title, string htmlContent, string emailTo, string emailToName = null) { if (title.IsNullOrEmpty() || htmlContent.IsNullOrEmpty() || emailTo.IsNullOrEmpty()) { return("发送失败,参数不允许为空!"); } var mailBo = new MailBo(IConfiguration) { MailToName = emailToName, MailTo = emailTo }; var mqMailBo = new MqMailBo() { MailBo = mailBo, Title = title, HtmlContent = htmlContent }; using (var channel = RabbitConnection.CreateModel()) { channel.QueueDeclare(queue: "LionEmailQueue", durable: true, exclusive: false, autoDelete: false, arguments: null); channel.ConfirmSelect(); //等待发送成功确认 var properties = channel.CreateBasicProperties(); properties.Persistent = true; //持久化 properties.MessageId = IdWorker.NextId().ToString(); //消息Id properties.Timestamp = new AmqpTimestamp(DateTime.Now.GetJsTimeStamp()); properties.Headers = new Dictionary <string, object>(); var bodyJson = mqMailBo.ToJson(); var body = Encoding.UTF8.GetBytes(bodyJson); channel.BasicPublish(exchange: "", routingKey: "LionEmailQueue", basicProperties: properties, body: body); var isOk = channel.WaitForConfirms(); if (isOk) { return("发送成功"); } //日志记录 LogHelper.Logger.Error($"邮件保存MQ失败,bodyJson:{bodyJson}"); return("发送异常"); } }
/// <summary> /// 重试 死信 测试 /// </summary> /// <param name="msg"></param> /// <returns></returns> public async Task <string> RetryDeadLetterMqSendAsync(string msg) { using (var channel = RabbitConnection.CreateModel()) { channel.ExchangeDeclare("TestExchange", ExchangeType.Direct, true); channel.QueueDeclare("TestQueue", true, false, false); channel.QueueBind("TestQueue", "TestExchange", "TestRouteKey"); channel.ConfirmSelect(); //等待发送确认 var properties = channel.CreateBasicProperties(); properties.Persistent = true; //设置为持久化 properties.MessageId = IdWorker.NextId().ToString(); //消息Id var body = msg.GetBytes(); channel.BasicPublish("TestExchange", "TestRouteKey", properties, body); var isOk = channel.WaitForConfirms(TimeSpan.FromSeconds(3)); if (isOk) { return("发送成功"); } } return("发送失败"); }