我开发了一个应用程序,可以向多个收件人发送电子邮件。要从收件人那里获取电子邮件,我正在使用自动填充功能,并用“,”分隔各个电子邮件,例如:aaa @ gmail.com,bbb @ gmail.com
问题在于,单击发送后,它不起作用,并且您收到以下错误:在邮件标题中发现无效字符:“,”。
控制器
[HttpPost]
[ValidateInput(false)]
public ActionResult Index(EmailModel model, List<HttpPostedFileBase> attachments)
{
model.Email = "xxxxx@gmail.com";
using (MailMessage mm = new MailMessage(model.Email, model.Destinatário))
{
mm.From = new MailAddress("xxxxx@gmail.com");
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>
答案 0 :(得分:1)
MailMessage
类不支持以逗号分隔的地址。而是将每个地址分别添加到To
成员中,
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("xxxxx@gmail.com");
model.Password = "xxxxx";
mm.Subject = model.Assunto;
mm.Body = model.Mensagem;
...
}
另请参阅:How to send Email to multiple Recipients with MailMessage?