[SOLVED] ASP.NET Core How to pass an IEnumerable String as a Variable in JavaScript

Issue

I would like to pass the To Mailbox Address as a parameter with multiple addresses using MimeKit to send a message.

If I edit the controller action to include a string with 2 email addresses:

var message = new Message(new string[] { "[email protected]","[email protected]" }, eMailSubject, eMailContent, null);

the message will be sent to both recipients [email protected] and [email protected]

However If I try to pass the parameter string eMailTo from the function email_valueChanged(e), I get the errors:

$exception {“Invalid addr-spec token at offset 0”}
x "\"[email protected]\",\"[email protected]\""

Is there a way to pass the eMailTo parameter for the IActionResult SendMessage within the javascript? Note that to is an IEnumerable string:

public Message(IEnumerable<string> to, string subject, string content, IFormFileCollection attachments)

I have also tried to pass the eMailTo parameter as an array with no luck.

Below are the details:

Function to send email from popup:

function showInfo(data) { location.href = '@Url.Action("SendMessage", "EMail")?eMailTo=' + eMailToAddress +'&eMailSubject=' + eMailSubject + '&eMailContent=' + eMailContent;}

<script>
    let eMailToAddress = -1;
    let eMailSubject = -1;
    let eMailContent = -1;

    function email_valueChanged(e) {
        eMailToAddress = '"[email protected]","[email protected]"';
        console.log("eMailToAddress = " + eMailToAddress);
    }
</script>

EMailController.cs

using EmailService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CPSPMO.Controllers
{
    public class EmailController : Controller
    {
        private readonly IEmailSender _emailSender;
        public EmailController(IEmailSender emailSender)
        {
            _emailSender = emailSender;   
        }

        public IActionResult SendMessage(string eMailTo, string eMailSubject, string eMailContent)
        {
            var message = new Message(new string[] { eMailTo }, eMailSubject, eMailContent, null);
            _emailSender.SendEmailAsync(message);

            return NoContent();
        }

    }
}

EMailConfiguration.cs

namespace EmailService
{
    public class EmailConfiguration
    {
        public string From { get; set; }   
        public string SmtpServer { get; set; }
        public int Port { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

EMailSender.cs

using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace EmailService
{
    public class EmailSender : IEmailSender
    {
        private readonly EmailConfiguration _emailConfig;
        public EmailSender(EmailConfiguration emailConfig)
        {
            _emailConfig = emailConfig; 
        }
        public void SendEmail(Message message)
        {
            var emailMessage = CreateEmailMessage(message);
            Send(emailMessage);
        }

        public async Task SendEmailAsync(Message message)
        {
            var mailMessage = CreateEmailMessage(message);
            await SendAsync(mailMessage);
        }
        private MimeMessage CreateEmailMessage(Message message)
        {
            var emailMessage = new MimeMessage();
            emailMessage.From.Add(new MailboxAddress(_emailConfig.From));
            emailMessage.To.AddRange(message.To);
            emailMessage.Subject = message.Subject;

            var bodyBuilder = new BodyBuilder { HtmlBody = String.Format("<h2 style='color:red'>{0}<h2>",message.Content) };
            if(message.Attachments != null && message.Attachments.Any())
            {
                byte[] fileBytes;
                foreach (var attachment in message.Attachments)
                {
                    using (var ms = new MemoryStream())
                    {
                        attachment.CopyTo(ms);
                        fileBytes = ms.ToArray();
                    }

                    bodyBuilder.Attachments.Add(attachment.FileName, fileBytes, ContentType.Parse(attachment.ContentType));
                }
            }

            emailMessage.Body = bodyBuilder.ToMessageBody();

            return emailMessage;    
        }


        private async Task SendAsync(MimeMessage mailMessage)
        {
            using (var client = new SmtpClient())
            {
                try
                {
                    await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, true);
                    await client.AuthenticateAsync(_emailConfig.Username, _emailConfig.Password);

                    await client.SendAsync(mailMessage);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    await client.DisconnectAsync(true);
                    client.Dispose();
                }
            }
        }
    }
}

IMailSender.cs
using System.Threading.Tasks;

namespace EmailService
{
    public interface IEmailSender   
    {
        void SendEmail(Message message);
        Task SendEmailAsync(Message message);
    }
}

Message.cs
using Microsoft.AspNetCore.Http;
using MimeKit;
using System.Collections.Generic;
using System.Linq;


namespace EmailService
{
    public class Message
    {
        public List<MailboxAddress> To { get; set; }
        public string Subject { get; set; }
        public string Content { get; set; }
        public IFormFileCollection Attachments { get; set; }
        public Message(IEnumerable<string> to, string subject, string content, IFormFileCollection attachments)
        {
            To = new List<MailboxAddress>();

            To.AddRange(to.Select(x => new MailboxAddress(x)));
            Subject = subject;
            Content = content;
            Attachments = attachments;
        }
    }
}

Solution

Please try to use string[] eMailTo, it should be useful to you.

 public string TestArray(string[] eMailTo,string eMailSubject)
 {
     StringBuilder msg = new StringBuilder();
     for (int i = 0; i < eMailTo.Length; i++)
     {
         msg.Append(eMailTo[i]);
         msg.Append(",");
     }
            
     return msg.Append(eMailSubject).ToString();
 }

Test Link:

https://localhost:44374/home/[email protected]&[email protected]&[email protected]&eMailSubject=testdata

Test Result:

enter image description here

Answered By – Jason Pan

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *