ecain ecain - 2 months ago 29
ASP.NET (C#) Question

"Contact us" page with ASP.NET Core - SMTP server issue

I'm new to web programming and am using ASP.NET core to make a website. I'm trying to create a standard "contact me" page where the user enters in a name, email, subject and username. I'm using the MailKit library to send the emails:

public IActionResult SendEmail(Contact contact)
{
var emailMessage = new MimeMessage();

emailMessage.From.Add(new MailboxAddress(contact.Name, contact.Email));
emailMessage.To.Add(new MailboxAddress("myname", "myemail"));
emailMessage.Subject = contact.Subject;
emailMessage.Body = new TextPart("plain") { Text = contact.Message };

using (var client = new SmtpClient())
{
client.Connect("smtp-mail.outlook.com", 587);
client.Authenticate("myemail", "myemailpassword");
client.Send(emailMessage);
client.Disconnect(true);
}
return RedirectToAction("Index", "Home");
}


My issue is that whenever I send the email the SMTP server just replaces my "from" header with my SMTP account information. This seems to be the case with not just outlook, but with every major SMTP server I've tried, including gmail. Is there an SMTP server that will not have this issue, or do I need to find another way of sending the emails?

Answer

First of all there is a problem with your code

    public IActionResult SendEmail(Contact contact)
    {
        var emailMessage = new MimeMessage();
        emailMessage.From.Add(new MailboxAddress("myname", "mymail@mail.com"));
        emailMessage.To.Add(new MailboxAddress("myname", "mymail@mail.com"));
        emailMessage.Subject = contact.Subject;
        emailMessage.Body = new TextPart("plain") 
        { 
         Text = String.Format("This visitor:{0} with this email:{1} Send this message:{2}", 
         contact.Name, contact.Email, contact.Message) 
        };

        using (var client = new SmtpClient())
        {
            client.Connect("smtp-mail.outlook.com", 587);
            client.Authenticate("myemail", "myemailpassword");
            client.Send(emailMessage);
            client.Disconnect(true);
        }
        return RedirectToAction("Index", "Home");
    }

Also visit the following question this may help you:

How to send an e-mail with C# through Gmail