I am using NetCore.MailKit NuGet package to help me send an email which contains a link to confirm their email when the user registers. I have followed the steps on their Github page but, I am getting an ArgumentNullException for the address, even though I have set the sending address.
The error:
ArgumentNullException: Value cannot be null. (Parameter 'address') MimeKit.MailboxAddress..ctor(Encoding encoding, string name, string address) The above error occurs when is send the email in my controller using IEmailService:
_EmailService.Send("[email protected]", "subject", "message body"); This is my appsettings.json configuration:
"EmailConfiguration": { "Server": "smtp.gmail.com", "Port": 587, "SenderName": "name", "SenderEmail": "[email protected]", "SenderPassword": "My gmail password" } This is my setup in startup.cs
services.AddMailKit(optionBuilder => { optionBuilder.UseMailKit(new MailKitOptions() { //get options from sercets.json Server = Configuration["Server"], Port = Convert.ToInt32(Configuration["Port"]), SenderName = Configuration["SenderName"], SenderEmail = Configuration["SenderEmail"], Account = Configuration["SenderEmail"], Password = Configuration["SenderPassword"], Security = true }); }); Below is the code for EmailService:
public void Send(string mailTo, string subject, string message, bool isHtml = false) { SendEmail(mailTo, null, null, subject, message, Encoding.UTF8, isHtml); } private void SendEmail(string mailTo, string mailCc, string mailBcc, string subject, string message, Encoding encoding, bool isHtml) { var _to = new string[0]; var _cc = new string[0]; var _bcc = new string[0]; if (!string.IsNullOrEmpty(mailTo)) _to = mailTo.Split(',').Select(x => x.Trim()).ToArray(); if (!string.IsNullOrEmpty(mailCc)) _cc = mailCc.Split(',').Select(x => x.Trim()).ToArray(); if (!string.IsNullOrEmpty(mailBcc)) _bcc = mailBcc.Split(',').Select(x => x.Trim()).ToArray(); Check.Argument.IsNotEmpty(_to, nameof(mailTo)); Check.Argument.IsNotEmpty(message, nameof(message)); var mimeMessage = new MimeMessage(); //add mail from mimeMessage.From.Add(new MailboxAddress(_MailKitProvider.Options.SenderName, _MailKitProvider.Options.SenderEmail)); //add mail to foreach (var to in _to) { mimeMessage.To.Add(MailboxAddress.Parse(to)); } //add mail cc foreach (var cc in _cc) { mimeMessage.Cc.Add(MailboxAddress.Parse(cc)); } //add mail bcc foreach (var bcc in _bcc) { mimeMessage.Bcc.Add(MailboxAddress.Parse(bcc)); } //add subject mimeMessage.Subject = subject; //add email body TextPart body = null; if (isHtml) { body = new TextPart(TextFormat.Html); } else { body = new TextPart(TextFormat.Text); } //set email encoding body.SetText(encoding, message); //set email body mimeMessage.Body = body; using (var client = _MailKitProvider.SmtpClient) { client.Send(mimeMessage); } } As you can see I have set everything, am I missing something here? why is address null at MimeKit.MailboxAddress()?
EmailServicewould be helpful