Answer the question
In order to leave comments, you need to log in
How to transfer to the user the data that he sent?
There are two services, apishka and smtp. Appointment for the purchase of some goods. When the user makes a purchase, he should receive an email that he ordered.
Endpoint for sending a purchase:
[HttpPost]
public async Task<IActionResult> Add(OrderCreateModel orderModel)
{
var orderAdd = _mapper.Map<OrderDto>(orderModel);
var orderCreated = await _orderService.AddAsync(orderAdd);
_messageService.Enqueue(orderCreated);
return CreatedAtAction(nameof(GetId), new { id = orderCreated.Id }, orderModel);
}
public Task StartAsync(CancellationToken cancellationToken)
{
var factory = new ConnectionFactory()
{
HostName = _rabbitSettings.Value.HostName,
UserName = _rabbitSettings.Value.UserName,
Password = _rabbitSettings.Value.Password,
Port = _rabbitSettings.Value.Port,
VirtualHost = _rabbitSettings.Value.VirtualHost,
AutomaticRecoveryEnabled = _rabbitSettings.Value.AutomaticRecoveryEnabled
};
IConnection connection = factory.CreateConnection();
IModel model = connection.CreateModel();
model.QueueDeclare(queue: "order",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(model);
consumer.Received += async (sender, e) =>
{
var body = Deserialize<Mail>(e.Body.ToArray());
await _mailService.SendMessageAsync(body);
};
model.BasicConsume("order", true, consumer);
return Task.CompletedTask;
}
public async Task SendMessageAsync(Mail mail)
{
var email = new MimeMessage();
email.Sender = MailboxAddress.Parse(_mailSettings.Value.Mail);
email.To.Add(MailboxAddress.Parse(mail.Email));
email.Subject = mail.Subject;
var builder = new BodyBuilder();
builder.HtmlBody = mail.Body;
email.Body = builder.ToMessageBody();
using var smtp = new SmtpClient();
smtp.Connect(_mailSettings.Value.Host, _mailSettings.Value.Port, SecureSocketOptions.StartTls);
smtp.Authenticate(_mailSettings.Value.Mail, _mailSettings.Value.Password);
await smtp.SendAsync(email);
smtp.Disconnect(true);
}
public class Mail
{
public string Email { get; set; } = "[email protected]";
public string Subject { get; set; } = "Greetings!";
public string Body { get; set; } = "Greetings!";
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question