I'm working a parser that's parsing and updating some raw Email headers and I realized while working on this that my mail component was not properly setting the mail headers when sending email. This code predates .NET 2.0 so I had originally created a custom component.
Sounds easy enough, but dates in email messages need to be Mime encoded. I figured there must be something in .NET that converts Time strings to Mime and GTM values, but after experimenting around with various time formats I couldn't find anything.
In the end I just created my own since I couldn't dig anything up in a pinch:
///
/// Converts the passed date time value to Mime formatted time string
///
///
public static string MimeDateTime(DateTime Time)
{
TimeSpan Offset = TimeZone.CurrentTimeZone.GetUtcOffset(Time);
string sOffset = null;
if (Offset.Hours < 0)
sOffset = "-" + (Offset.Hours * -1).ToString().PadLeft(2, '0');
else
sOffset = "+" + Offset.Hours.ToString().PadLeft(2, '0');
sOffset += Offset.Minutes.ToString().PadLeft(2, '0');
return "Date: " + DateTime.Now.ToString("ddd, dd MMM yyyy hh:mm:ss",
System.Globalization.CultureInfo.InvariantCulture) +
" " + sOffset;
}
Interesting thing happened while I was screwing around with this: I thought it would be much easier to use Utc time and assign a 0000 time offset. So the following actually works as well:
string Time = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture) + " +0000";
but this relies on the mail client fixing up the date time for sure and doesn't give any idea about the client's timezone. So I think the lengthier version is the right way to get the time to return.
BTW, to get GMT format time you can use this code just fine:
string Time = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture) + " GMT";
I'm sure I'm missing some built-in way to do this, but here it is just in case .
Other Posts you might also like