user10186430
user10186430

Reputation:

Asp.Net MVC Email: An invalid character was found in the mail header

I developed an application that allows sending an email to several recipients. To fetch the emails from the recipients, I am using an autocomplete and separate the various emails by "," Example: aaa @ gmail.com, bbb @ gmail.com

The problem is that when the click to send, it does not work and you receive the following error: An invalid character was found in the mail header: ','.

Image of error

Controller

[HttpPost]
        [ValidateInput(false)]
        public ActionResult Index(EmailModel model, List<HttpPostedFileBase> attachments)
        {
            model.Email = "[email protected]";
            using (MailMessage mm = new MailMessage(model.Email, model.Destinatário))
            {
                mm.From = new MailAddress("[email protected]");
                model.Password = "xxxxx";
                mm.Subject = model.Assunto;
                mm.Body = model.Mensagem;

                foreach (HttpPostedFileBase attachment in attachments)
                {
                    if (attachment != null)
                    {
                        string fileName = Path.GetFileName(attachment.FileName);
                        mm.Attachments.Add(new Attachment(attachment.InputStream, fileName));
                    }
                }
                mm.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.EnableSsl = true;
                NetworkCredential NetworkCred = new NetworkCredential(model.Email, model.Password);
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = NetworkCred;
                smtp.Port = 587;
                smtp.Send(mm);
                ViewBag.Message = "Sucess!";
            }
            return View();
        }

JavaScript

 <script type="text/javascript">
        $(function () {

            $("#email").autocomplete({
                source: function (request, response) {
                    $.ajax(
                        {
                            url: '/Email/AutoComplete/',
                            data: "{ 'prefix': '" + GetCurrentSearchTerm(request.term) + "'}",
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            cache: false,
                            success: function (data) {
                                response($.map(data, function (item) {
                                    return {
                                        label: item.label,
                                        value: item.val,
                                        nome: item.val
                                    };
                                }))
                            }
                        })
                },
                select: function (event, ui) {
                    var LastValue = splitCurrentText(this.value);
                    LastValue.pop();
                    LastValue.push(ui.item.value);
                    LastValue.push("");
                    this.value = LastValue.join(",");
                    return false;
                },
                focus: function () {
                    return false;
                }
            });
            function splitCurrentText(LastTerm) {

                return LastTerm.split(/,\s*/);
            }

            function GetCurrentSearchTerm(LastTerm) {

                return splitCurrentText(LastTerm).pop();
            }
        });
    </script>

Upvotes: 1

Views: 1143

Answers (1)

Dean Goodman
Dean Goodman

Reputation: 983

The MailMessage class does not support comma-separated addresses. Instead, add each address separately to the To member, like so.

using (MailMessage mm = new MailMessage())
{
    var toAddresses = model.Destinatário.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries);

    foreach (var toAddress in toAddresses)
    {
        mm.To.Add(new MailAddress(toAddress));
    }

    mm.From = new MailAddress("[email protected]");
    model.Password = "xxxxx";
    mm.Subject = model.Assunto;
    mm.Body = model.Mensagem;
    ...
}

See also: How to send Email to multiple Recipients with MailMessage?

Upvotes: 1

Related Questions