简体   繁体   中英

Can MailKit be used for “Contact Me” form?

I'm new to web programming and I am making a website using ASP.NET Core. I am trying to create a standard "contact me" page where the user enters in a name, email, subject and message. ASP.NET Core has yet to have System.Net.Mail , so I can't use that.

I saw that MailKit could be used to send emails, but am unable to figure out how to use it for a contact page. I know using this code

 using (var client = new SmtpClient ()) {
            client.Connect ("smtp.friends.com", 587, false);

            // Note: since we don't have an OAuth2 token, disable
            // the XOAUTH2 authentication mechanism.
            client.AuthenticationMechanisms.Remove ("XOAUTH2");

            // Note: only needed if the SMTP server requires authentication
            client.Authenticate ("joey", "password");

            client.Send (message);
            client.Disconnect (true);

I can send an email using my SMTP server, but obviously I want the functionality of users using the site to be able to send an email to me. Is there a way to use MailKit for this, or do I need to find another solution? Thanks.

Edit: This is the code I have that successfully sends an email, but it always says that it was sent from me to me.

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");
    }

Yes, MailKit can be used for this purpose.

The problem you are seeing is because outlook.com is replacing your From header with your email address (it's a "feature" of outlook.com when you login via SMTP).

You might be able to sort of work around this by setting the ReplyTo to the user's address (so you can reply to them).

Or you could try setting the From to the user's address and setting the Sender to your address (not sure if this will work).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM