MVC net core 1.1.0 Mailkit sending a mail form returning a blank page

203 views Asked by At

What's wrong with this code - I just want to redirect after succesfuld sending:

public async Task SendEmailAsync(string Email, string Name, string Message) { var emailMessage = new MimeMessage();

        emailMessage.From.Add(new MailboxAddress("PAR OG SINGLER", "[email protected]"));
        emailMessage.To.Add(new MailboxAddress("per", Email));
        emailMessage.Subject = "Test par og singler";
        emailMessage.Body = new TextPart("plain") { Text = Message };

        using (var client = new SmtpClient())
        {
            var credentials = new NetworkCredential
            {
                UserName = "[email protected]", // replace with valid value
                Password = "detteerentest" // replace with valid value
            };
            //var mytask = Email + "" + Message;

            client.LocalDomain = "parogsingler.dk";
            await client.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.Auto).ConfigureAwait(false);
            client.AuthenticationMechanisms.Remove("XOAUTH2");

            await client.AuthenticateAsync(credentials);

            await client.SendAsync(emailMessage).ConfigureAwait(false);
            await client.DisconnectAsync(true).ConfigureAwait(false);

            RedirectToAction("Thanks");
        }
    }
    public IActionResult Thanks()
    {
        return View();
    }
1

There are 1 answers

0
Johan Herstad On

I don't know why you would use RedirectToAction there. I don't think it can be used within a method that is not an actionresult. The purpose of that method is to call another actionmethod where you then have code to run. But you don't, so you can just call View("thanks") directly from whatever actionmethod you are in.

You should make a separate class for you Email method, and then call that class from the controller.

This way you only have to call your email methods in one line in the actionmethod that triggers it. It will save alot of work. This example calls the email class EmailService and it's sendmail method:

Public async Task<IActionResult> Mail()
{
   //maybe some validation or/and exeption handling

     var emailService = new EmailService();
     await emailService.SendEmailAsync();
     return View("Thanks");

  //errormessage if not succeed

}
public IActionResult Thanks()
{
    return View();
}

Ideally you want to use dependency injecton to set up an emailservice. In your controller(or some other class) you can then call your email class by instantiating it in the constructor.