I’m using System.Net.Mail
to send email in my application but I get an exception and I can’t figure out what/where the problem is and how to fix it.
The error says I have some invalid char:
An invalid character was found in the mail header: ‘;’.
I tried google without success.
The string with email address is:
john@mydomain.org; beth@mydomain.org; alfred@mydomain.org; barbie@mydomain.org;
Here is my email sending code:
SmtpClient smtpClient = new SmtpClient("smtp.........");
System.Net.Mail.MailMessage mailMessagePlainText = new System.Net.Mail.MailMessage();
mailMessagePlainText.IsBodyHtml = true;
mailMessagePlainText.From = new MailAddress("vincent@mydomain.org", "admin");
mailMessagePlainText.Subject = "test";
mailMessagePlainText.Body = "test";
mailMessagePlainText.To.Add(new MailAddress(List1.ToString(), ""));
mailMessagePlainText.Bcc.Add(new MailAddress("vincent@mydomain.org", ""));
try
{
smtpClient.Send(mailMessagePlainText);
}
catch (Exception ex)
{
throw (ex);
}
Dale K
24.9k15 gold badges42 silver badges71 bronze badges
asked Jul 1, 2015 at 7:28
Antonio MailtraqAntonio Mailtraq
1,3875 gold badges33 silver badges82 bronze badges
5
foreach (var address in List1.split(';')) {
mailMessagePlainText.To.Add(new MailAddress(address.Trim(), ""));
}
Because according to your string here above, each address in this loop above would produce following:
"john@mydomain.org"
" beth@mydomain.org"
" alfred@mydomain.org"
" barbie@mydomain.org"
So by adding .Trim()
to address would make your code work.
Dale K
24.9k15 gold badges42 silver badges71 bronze badges
answered Jul 1, 2015 at 7:47
2
A MailAddressCollection
(like your mailMessagePlainText.To
) has an Add
method that accepts a string containing a list of mail addresses, separated by a comma.
So to use that, you will need to change the ;
into a ,
and possibly remove the extra spaces.
answered Jul 1, 2015 at 7:52
Hans KestingHans Kesting
37.9k9 gold badges78 silver badges111 bronze badges
1
It looks like you’re adding the addresses as a single MailAddress, where you need to add them 1 at a time. I don’t know what other overloads are available, but the following will probably work.
I split the string by ;
and add each address separately.
replace
mailMessagePlainText.To.Add(new MailAddress(List1.ToString(), ""));
with
foreach (var address in List1.split(';')) {
mailMessagePlainText.To.Add(new MailAddress(address , ""));
}
answered Jul 1, 2015 at 7:39
MeanGreenMeanGreen
3,0485 gold badges36 silver badges62 bronze badges
2
|
|
|
[!] Как относитесь к модерированию на этом форуме? Выскажите свое мнение здесь
Ошибка при загрузке XML файла
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Senior Member Рейтинг (т): 1 |
После компиляции при запуске выскакивает ошибка _xml->LoadFromXML(OpenDialog1->FileName); Вот весь код void __fastcall TForm1::Button1Click(TObject *Sender) { // Создаем объект типа _di_IXMLDocument _di_IXMLDocument _xml = NewXMLDocument(); if (!OpenDialog1->Execute()) exit(-1); Memo2->Lines->Clear(); // Загружаем в него файл _xml->LoadFromXML(OpenDialog1->FileName); //Делаем активным _xml->Active = true; Memo1->Lines->Add(_xml->ChildNodes->Nodes[WideString(«UNIT»)]->Text); _xml->Active = false; } Содержание XML файла Добавлено 01.04.08, 15:45 Помогите пожалуйста. Добавлено 01.04.08, 16:06 вместо Memo2->Lines->Clear(); Надо Memo1->Lines->Clear(); |
Диссидент |
|
1. XML-файл должен начинаться строкой вида <?xml version=»1.0″ encoding=»UTF-8″?> Цитата <UNIT DELIMITER=»1″><=</UNIT> В этих двух строках — ошибки. Уточни синтаксис для корректного ввода >= и <= (что-то типа &le, &ge — врать не буду, не помню). К твоему файлу я добавил заголовок, убрал две проблемные строки и сохранил его в UTF-8. Интернет Эксплорер схавал Цитата <?xml version=»1.0″ encoding=»UTF-8″?> Добавлено 01.04.08, 16:32 Цитата Диссидент @ 01.04.08, 16:26 что-то типа &le, &ge — врать не буду, не помню Наврал — больше или равно — сами символы надо отделить пробелами от угловых скобок : <UNIT DELIMETER=»1″> >= </UNIT>. |
zuze |
|
Senior Member Рейтинг (т): 1 |
Internet Explorer у меня с изначально работал с этим XML файлом и без изменений в нём. |
Диссидент |
|
|
zuze |
|
Senior Member Рейтинг (т): 1 |
Ну а толку я для большей надёжности эти строчки не закомментировал, а вообще удалил. Не работает. |
trainer |
|
ну так удали из XML все строчки кроме одной и посмотри, что будет. Потом добавляй по одной и снова смотри. Найдешь строку, из-за которой возникает ошибка — приходи. P.S. символ ‘<‘ в последовательности «<=» все же надо заменить на > |
zuze |
|
Senior Member Рейтинг (т): 1 |
Удалил почти всё. Вот так выгядит XML файл <TTC> Ошибка Project LexicalAnaliz.exe raised exception class EDOMParseError with message ‘An invalid character was found in text content’ в первой строке, добавляв в первую строчку <?xml version=»1.0″ encoding=»UTF-8″?> непомогло. Что же я не так делаю? |
SVK |
|
Цитата zuze @ 02.04.08, 05:40 encoding=»UTF-8″ попробуй encoding=»WINDOWS-1251″ |
zuze |
|
Senior Member Рейтинг (т): 1 |
encoding=»WINDOWS-1251″ Непомогло. |
Диссидент |
|
Блин! Заголовок полностью записан? <?xml version=»1.0″ encoding=»UTF-8″?> <!— или так : —> <?xml version=»1.0″ encoding=»Windows-1251″?> Если не секрет — приаттач сам файл. Мож там внутри ещё что-то есть? Чем он создан — ручками или программно? Повторил твой эксперимент из трёх строк <?xml version=»1.0″ encoding=»UTF-8″?> <TTC> </TTC> всё ОК! Цитата zuze @ 02.04.08, 05:40 Ошибка Project LexicalAnaliz.exe raised Ещё момент — чем открываешь? TXMLDocument‘ом? |
zuze |
|
Senior Member Рейтинг (т): 1 |
Набиваю XML руками. <?xml version=»1.0″ encoding=»UTF-8″?> <TTC> </TTC> В Internet Explorer работает без ошибок, а в коде который я написал в самом начале неработает. Текст XML файла в Memo1 не выводится. Добавлено 02.04.08, 16:15 Большое спасибо. |
Диссидент |
|
Цитата zuze @ 02.04.08, 16:03 Текст XML файла в Memo1 не выводится. Utf8ToAnsi() тебе в помощь |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Borland C++ Builder/Turbo C++ Explorer
- Следующая тема
[ Script execution time: 0,0399 ] [ 16 queries used ] [ Generated: 9.06.23, 19:53 GMT ]
Mail headers are an essential part of any email communication, as they provide information about the sender, recipient, and other details of the email. However, sometimes mail headers may contain invalid characters, leading to issues in the email delivery process. In this guide, we will discuss how to identify and resolve invalid character errors in mail headers.
Table of Contents
- Understanding Mail Headers
- Identifying Invalid Characters in Mail Headers
- Resolving Invalid Character Errors
- FAQs
Understanding Mail Headers
Before diving into the solutions, it is essential to understand what mail headers are and how they work. Mail headers are a series of lines in an email that provide information about the email’s origin, destination, and other metadata. Some common mail header fields include:
From
: Specifies the sender’s email addressTo
: Specifies the recipient’s email addressSubject
: Provides the email subjectDate
: Indicates the date and time the email was sentContent-Type
: Specifies the email content format (e.g., text/plain, text/html)
For more information on mail headers and their format, you can refer to the RFC 5322 standard.
Invalid characters in mail headers can cause various issues, such as email delivery failures or incorrect display of email content. The most common invalid characters are non-ASCII characters or control characters.
To identify invalid characters in mail headers, you can use the following methods:
- Manual inspection: Open the email source (usually available in the email client’s «View Source» or «Show Original» option) and examine the mail headers for any unusual or non-ASCII characters.
- Regular expressions: Use regular expressions to search for non-ASCII or control characters in the mail headers. For example, you can use the following regex to find non-ASCII characters:
/[^x00-x7F]/
. Similarly, you can use/[x00-x1Fx7F]/
to find control characters.
Resolving Invalid Character Errors
Once you have identified the invalid characters in the mail headers, you can follow these steps to resolve the errors:
- Remove or replace invalid characters: Remove the invalid characters from the mail headers or replace them with valid ASCII characters. Ensure that you don’t change the header field’s semantics while making these modifications.
- Use MIME encoding for non-ASCII characters: If you need to use non-ASCII characters in mail headers, consider using MIME encoding. This encoding allows you to use non-ASCII characters in mail headers without causing any issues. For example, you can encode a non-ASCII subject as follows:
Subject: =?UTF-8?B?U29tZSBub24tQVNDSUkgY2hhcmFjdGVycw==?=
. - Verify email generation code: If you are using a programming language or library to generate emails, ensure that the code or library is correctly handling mail headers and not introducing invalid characters. Check the documentation and ensure that you are using the appropriate functions or methods to set mail header fields.
FAQs
According to the RFC 5322 standard, mail headers can contain printable ASCII characters (excluding control characters) and some whitespace characters (space and horizontal tab). Non-ASCII characters and control characters are not allowed in mail headers unless properly encoded using MIME encoding.
Invalid characters in mail headers can cause email delivery issues because they may not be correctly interpreted by email clients or mail transfer agents (MTAs). This can lead to mail being rejected, marked as spam, or misinterpreted by the recipients.
3. How do I check if my email client is correctly handling mail headers?
To check if your email client is correctly handling mail headers, send a test email with various header fields and examine the received email’s headers. You can use tools like mail-tester to analyze your emails for any issues related to mail headers or email deliverability.
You can use Unicode characters in mail headers, but they must be properly encoded using MIME encoding. This ensures that the characters are represented as ASCII characters in the mail headers and do not cause any issues during email delivery.
5. Are there any tools available to test and validate mail headers?
There are several tools available to test and validate mail headers, such as mail-tester, MX Toolbox, and Google’s Message Header Analyzer. These tools can help you identify issues related to mail headers and provide suggestions for resolving them.
- RFC 5322 — Internet Message Format
- RFC 2047 — MIME (Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for Non-ASCII Text
- Email Deliverability Best Practices
- Using Unicode in Email Headers
<font color="blue">Public</font> <font color="blue">Function</font> ToUnicode(txt <font color="blue">As</font> String) <font color="blue">As</font> String Dim strText1, ss strText1 = <font color="red">""</font> <font color="blue">For</font> ss = <font color="darkblue"><b>1</b></font> <font color="blue">To</font> <font color="magenta">Len</font>(txt) strText1 = strText1 & <font color="red">"&#"</font> & AscW(Mid(txt, ss, <font color="darkblue"><b>1</b></font>)) & <font color="red">";"</font> <font color="blue">Next</font> ss ToUnicode = strText1 <font color="blue">End</font> <font color="blue">Function</font>
- Remove From My Forums
-
Question
-
Hi Gurus,
I was reading from a xml doc using Visual basic. I was doing it fine until i got this error message in my browser, when i was trying to open that xml file, i got the following error- An invalid character was found in text content. Error processing resource ‘file:///C:/EAL-00056-082.xml’. Line 1, Position…
I tried to look into what was the issue.
and found that the text that was inside a xml tag, had an apostrophe ‘s. ie(Land’s Motion) and hence i was not able to see the xml file generated on the browser, once i remove the single quote of the apostrophe i am able to open the document in the browser.
Is there a way how i can overcome this problem of singlequote in the text content of the xml file??? so that i am able to open the file in a browser.
Can i replace the single quote with something else, How is it handled whille in VB.
Thanking you in Anticipation,
Sachin.
Answers
-
When you load an XML document in a browser like IE then the browser uses its XML parser (in case of IE that parser is MSXML) to check the XML for well-formedness. That particular document where you get the error is not well-formed, probably because it is not properly encoded. You need to fix that at the source so that whoever generates the XML makes sure it is properly encoded and declares the encoding if needed (i.e. when it is not UTF-8 or UTF-16).
If you want to fix the document at your end then you can’t use any XML APIs to do that as the document is not well-formed. And the first thing you need to know to fix the document is the encoding of the document so ask the producer of the document how it is encoded. If you know the encoding then you can read it in with a TextReader and add the XML declaration or change the encoding when saving back. So this overload http://msdn.microsoft.com/en-us/library/ms143456.aspx of the StreamReader constructor which takes a stream and an encoding for instance which you can use once you know the encoding. Or try encodings you suspect to be used.
To make it clear: the single quote itself is not a problem at all in XML, here is an example document that has it and you can easily load that in IE without getting an error: http://home.arcor.de/martin.honnen/xml/test2008070501.xml
So the problem is not a single quote but an improperly encoded or declared XML document. You need to find out how the producer of that document encoded the document. So ask in a support forum for Siebel CRM how that software encodes its XML documents or how you can use that software to properly encode the XML documents it produces.