internal void EncodeHeaders(HeaderCollection headers, bool allowUnicode)
{
if (_headersEncoding == null)
{
_headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
}
System.Diagnostics.Debug.Assert(_headersEncoding != null);
for (int i = 0; i < headers.Count; i++)
{
string headerName = headers.GetKey(i);
//certain well-known values are encoded by PrepareHeaders and PrepareEnvelopeHeaders
//so we can ignore them because either we encoded them already or there is no
//way for the user to have set them. If a header is well known and user settable then
//we should encode it here, otherwise we have already encoded it if necessary
if (!MailHeaderInfo.IsUserSettable(headerName))
{
continue;
}
string[] values = headers.GetValues(headerName);
string encodedValue = string.Empty;
for (int j = 0; j < values.Length; j++)
{
//encode if we need to
if (MimeBasePart.IsAscii(values[j], false)
|| (allowUnicode && MailHeaderInfo.AllowsUnicode(headerName) // EAI
&& !MailBnfHelper.HasCROrLF(values[j])))
{
encodedValue = values[j];
}
else
{
encodedValue = MimeBasePart.EncodeHeaderValue(values[j],
_headersEncoding,
MimeBasePart.ShouldUseBase64Encoding(_headersEncoding),
headerName.Length);
}
//potentially there are multiple values per key
if (j == 0)
{
//if it's the first or only value, set will overwrite all the values assigned to that key
//which is fine since we have them stored in values[]
headers.Set(headerName, encodedValue);
}
else
{
//this is a subsequent key, so we must Add it since the first key will have overwritten the
//other values
headers.Add(headerName, encodedValue);
}
}
}
}