简体   繁体   中英

How to Send an email through “Contact us” Form using Mailkit in asp.net core

Hello everyone!

I have problem sending an email using Contact form. The goal is so that user enters his email address, subject and message and the email shows up in my mailbox. The problem I'm having is that the email doesn't come from the email address that user has entered but from the address which is supposed to receive the message. Basically I keep sending emails to myself. I have no problem sending email to user eg invoice or order status...

I've tried to run my app in Debug mode and everything seems fine. Post method model has values I entered and SendEmail method is not replacing "FROM ADDRESS" with my address.

private string recipientAddress = "myaddress@domain.com"

 public IActionResult Contact(ContactViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View();
        }
        emailSender.SendEmail(recipientAddress, model.Subject, model.EmailBody, model.SenderEmail);
        return RedirectToAction("Index");
    }

public void SendEmail(string recipient, string subject, string emailBody, string emailSender = null)
    {
        string smtpServer = emailConfiguration.SmtpServer;
        int smtpPort = emailConfiguration.SmtpPort;
        string smtpUsername = emailConfiguration.SmtpUsername;
        string smtpPassword = emailConfiguration.SmtpPassword;

        var message = new MimeMessage();
        var fromAddress = string.IsNullOrEmpty(emailSender) ? smtpUsername : emailSender;
        message.To.Add(new MailboxAddress(recipient));
        message.From.Add(new MailboxAddress(fromAddress));
        message.Subject = subject;
        message.Body = new TextPart(TextFormat.Html)
        {
            Text = emailBody
        };

        using (var smtpClient = new SmtpClient())
        {              
            smtpClient.Connect(smtpServer, smtpPort);

            smtpClient.AuthenticationMechanisms.Remove("XOAUTH2");
            smtpClient.Authenticate(smtpUsername, smtpPassword);
            smtpClient.Send(message);
            smtpClient.Disconnect(true);
        }
    }

如果许多SMTP服务器(例如GMail)不匹配,它们就会将“发件人”地址替换为用于身份验证的地址。

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