📄 mailmessage.cs
字号:
///</summary>
/// <param name="mailheader">MailHeader instance</param>
/// <example>
/// <code>
/// MailMessage msg = new MailMessage("support@OpenSmtp.com", "recipient@OpenSmtp.com");
/// MailHeader header = new MailHeader("X-Something", "HeaderValue");
/// msg.AddCustomHeader(header);
/// </code>
/// </example>
public void AddCustomHeader(MailHeader mailheader)
{
if (mailheader.name != null && mailheader.body != null)
{
customHeaders.Add(mailheader);
}
}
/// <summary>Populates the Body property of the MailMessage from a text file</summary>
/// <param name="filePath">Path to the file containing the MailMessage body</param>
/// <example>
/// <code>
/// MailMessage msg = new MailMessage("support@OpenSmtp.com", "recipient@OpenSmtp.com");
/// msg.GetBodyFromFile(@"C:\body.txt");
/// </code>
/// </example>
public void GetBodyFromFile(string filePath)
{
this.body = GetFileAsString(filePath);
}
/// <summary>Populates the HtmlBody property of the MailMessage from a HTML file</summary>
/// <param name="filePath">Path to the file containing the MailMessage html body</param>
/// <example>
/// <code>
/// MailMessage msg = new MailMessage("support@OpenSmtp.com", "recipient@OpenSmtp.com");
/// msg.GetHtmlBodyFromFile(@"C:\htmlbody.html");
/// </code>
/// </example>
public void GetHtmlBodyFromFile(string filePath)
{
// add extension
this.htmlBody = GetFileAsString(filePath);
}
/// <summary>Resets all of the MailMessage properties</summary>
/// <example>
/// <code>
/// MailMessage msg = new MailMessage("support@OpenSmtp.com", "recipient@OpenSmtp.com");
/// msg.Reset();
/// </code>
/// </example>
public void Reset()
{
from = null;
replyTo = null;
recipientList.Clear();
ccList.Clear();
bccList.Clear();
customHeaders.Clear();
attachments.Clear();
subject = null;
body = null;
htmlBody = null;
priority = null;
mixedBoundary = null;
altBoundary = null;
charset = null;
notification = false;
}
/// <summary>Saves the MailMessage as a RFC 822 formatted message</summary>
/// <param name="filePath">Specifies the file path to save the message</param>
/// <example>
/// <code>
/// MailMessage msg = new MailMessage("support@OpenSmtp.com", recipient@OpenSmtp.com");
/// msg.Body = "body";
/// msg.Subject = "subject";
/// msg.Save(@"C:\email.txt");
/// </code>
/// </example>
public void Save(string filePath)
{
StreamWriter sw = File.CreateText(filePath);
sw.Write(this.ToString());
sw.Close();
}
/// <summary>Returns the MailMessage as a RFC 822 formatted message</summary>
/// <example>
/// <code>
/// MailMessage msg = new MailMessage("support@OpenSmtp.com", "recipient@OpenSmtp.com");
/// msg.Body = "body";
/// msg.Subject = "subject";
/// string message = msg.ToString();
/// </code>
/// </example>
/// <returns>Mailmessage as RFC 822 formatted string</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if (ReplyTo.name != null && ReplyTo.name.Length != 0)
{
sb.Append("Reply-To: " + MailEncoder.ConvertHeaderToQP(ReplyTo.name, charset) + " <" + ReplyTo.address + ">\r\n");
}
else
{
sb.Append("Reply-To: <" + ReplyTo.address + ">\r\n");
}
if (from.name != null && from.name.Length != 0)
{
sb.Append("From: " + MailEncoder.ConvertHeaderToQP(from.name, charset) + " <" + from.address + ">\r\n");
}
else
{
sb.Append("From: <" + from.address + ">\r\n");
}
sb.Append("To: " + CreateAddressList(recipientList) + "\r\n");
if (ccList.Count != 0)
{
sb.Append("CC: " + CreateAddressList(ccList) + "\r\n");
}
if (subject != null && subject.Length > 0)
{
sb.Append("Subject: " + MailEncoder.ConvertHeaderToQP(subject, charset) + "\r\n");
}
sb.Append("Date: " + DateTime.Now.ToUniversalTime().ToString("R") + "\r\n");
sb.Append(SmtpConfig.X_MAILER_HEADER + "\r\n");
if (notification)
{
if (ReplyTo.name != null && ReplyTo.name.Length != 0)
{
sb.Append("Disposition-Notification-To: " + MailEncoder.ConvertHeaderToQP(ReplyTo.name, charset) + " <" + ReplyTo.address + ">\r\n");
}
else
{
sb.Append("Disposition-Notification-To: <" + ReplyTo.address + ">\r\n");
}
}
if (priority != null)
{
sb.Append("X-Priority: " + priority + "\r\n");
}
if (customHeaders != null)
{
for (IEnumerator i = customHeaders.GetEnumerator(); i.MoveNext();)
{
MailHeader m = (MailHeader)i.Current;
if (m.name.Length >= 0 && m.body.Length >= 0)
{
sb.Append(m.name + ":" + MailEncoder.ConvertHeaderToQP(m.body, charset) + "\r\n");
}
else
{
// TODO: Check if below is within RFC spec.
sb.Append(m.name + ":\r\n");
}
}
/*
for (int i=0; i < customHeaders.Count; i++)
{
sb.Append(customHeaders.Keys[i]);
sb.Append(": ");
sb.Append(MailEncoder.ConvertHeaderToQP(customHeaders[customHeaders.Keys[i]], charset));
sb.Append("\r\n");
}
*/
}
sb.Append("MIME-Version: 1.0\r\n");
sb.Append(GetMessageBody());
return sb.ToString();
}
/// <summary>Returns a clone of this message</summary>
/// <example>
/// <code>
/// MailMessage msg = new MailMessage("support@OpenSmtp.com", "recipient@OpenSmtp.com");
/// msg.Body = "body";
/// msg.Subject = "subject";
///
/// msg2 = msg.Copy();
/// </code>
/// </example>
/// <returns>Mailmessage</returns>
public MailMessage Copy()
{
return (MailMessage)this.MemberwiseClone();
}
/// Internal/Private methods below
// ------------------------------------------------------
private string GetFileAsString(string filePath)
{
FileStream fin = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] bin = new byte[fin.Length];
long rdlen = 0;
int len;
StringBuilder sb = new StringBuilder();
while(rdlen < fin.Length)
{
len = fin.Read(bin, 0, (int)fin.Length);
sb.Append(Encoding.UTF7.GetString(bin, 0, len));
rdlen = (rdlen + len);
}
fin.Close();
return sb.ToString();
}
/// <summary>
/// Determines the format of the message and adds the
/// appropriate mime containers.
///
/// This will return the html and/or text and/or
/// embedded images and/or attachments.
/// </summary>
/// <returns></returns>
private String GetMessageBody()
{
StringBuilder sb=new StringBuilder();
if (attachments.Count>0)
{
sb.Append("Content-Type: multipart/mixed;");
sb.Append("boundary=\"" + mixedBoundary + "\"");
sb.Append("\r\n\r\nThis is a multi-part message in MIME format.");
sb.Append("\r\n\r\n--" + mixedBoundary + "\r\n");
}
sb.Append(GetInnerMessageBody());
if (attachments.Count>0)
{
foreach (Attachment attachment in attachments)
{
sb.Append("\r\n\r\n--" + mixedBoundary + "\r\n");
sb.Append(attachment.ToMime());
}
sb.Append("\r\n\r\n--" + mixedBoundary + "--\r\n");
}
return sb.ToString();
}
/// <summary>
/// Get the html and/or text and/or images.
/// </summary>
/// <returns></returns>
private string GetInnerMessageBody()
{
StringBuilder sb=new StringBuilder();
if (images.Count > 0)
{
sb.Append("Content-Type: multipart/related;");
sb.Append("boundary=\"" + relatedBoundary + "\"");
sb.Append("\r\n\r\n--" + relatedBoundary + "\r\n");
}
sb.Append(GetReadableMessageBody());
if (images.Count > 0)
{
foreach (Attachment image in images)
{
sb.Append("\r\n\r\n--" + relatedBoundary + "\r\n");
sb.Append(image.ToMime());
}
sb.Append("\r\n\r\n--" + relatedBoundary + "--\r\n");
}
return sb.ToString();
}
private String GetReadableMessageBody() {
StringBuilder sb=new StringBuilder();
if (htmlBody == null)
{
sb.Append(GetTextMessageBody(body, "text/plain"));
}
else if (body == null)
{
sb.Append(GetTextMessageBody(htmlBody, "text/html"));
}
else
{
sb.Append(GetAltMessageBody(
GetTextMessageBody(body, "text/plain"),
GetTextMessageBody(htmlBody, "text/html")));
}
return sb.ToString();
}
private string GetTextMessageBody(string messageBody, string textType)
{
StringBuilder sb = new StringBuilder();
sb.Append("Content-Type: " + textType + ";\r\n");
sb.Append(" charset=\""+ charset + "\"\r\n");
sb.Append("Content-Transfer-Encoding: quoted-printable\r\n\r\n");
sb.Append(MailEncoder.ConvertToQP(messageBody, charset));
return sb.ToString();
}
private string GetAltMessageBody(string messageBody1, string messageBody2)
{
StringBuilder sb = new StringBuilder();
sb.Append("Content-Type: multipart/alternative;");
sb.Append("boundary=\"" + altBoundary + "\"");
sb.Append("\r\n\r\nThis is a multi-part message in MIME format.");
sb.Append("\r\n\r\n--" + altBoundary + "\r\n");
sb.Append(messageBody1);
sb.Append("\r\n\r\n--" + altBoundary + "\r\n");
sb.Append(messageBody2);
sb.Append("\r\n\r\n--" + altBoundary + "--\r\n");
return sb.ToString();
}
// creates comma separated address list from to: and cc:
private string CreateAddressList(ArrayList msgList)
{
StringBuilder sb = new StringBuilder();
int index = 1;
int msgCount = msgList.Count;
for (IEnumerator i = msgList.GetEnumerator(); i.MoveNext(); index++)
{
EmailAddress a = (EmailAddress)i.Current;
// if the personal name exists, add it to the address sent. IE: "Ian Stallings" <istallings@mail.com>
if (a.name != null && a.name.Length > 0)
{
//sb.Append("=?" + charset + "?Q?" + MailEncoder.ConvertToQP(a.name, charset) + "?= <" + a.address + ">");
sb.Append(MailEncoder.ConvertHeaderToQP(a.name, charset) + " <" + a.address + ">");
}
else
{
sb.Append("<" + a.address + ">");
}
// if it's not the last address add a semi-colon:
if (msgCount != index)
{
sb.Append(";");
}
}
return sb.ToString();
}
private static string generateMixedMimeBoundary()
{
// Below generates uniqe boundary for each message. These are used to separate mime parts in a message.
return "Part." + Convert.ToString(new Random(unchecked((int)DateTime.Now.Ticks)).Next()) + "." + Convert.ToString(new Random(~unchecked((int)DateTime.Now.Ticks)).Next());
}
private static string generateAltMimeBoundary()
{
// Below generates uniqe boundary for each message. These are used to separate mime parts in a message.
return "Part." + Convert.ToString(new Random(~unchecked((int)DateTime.Now.AddDays(1).Ticks)).Next()) + "." + Convert.ToString(new Random(unchecked((int)DateTime.Now.AddDays(1).Ticks)).Next());
}
private static string generateRelatedMimeBoundary()
{
// Below generates uniqe boundary for each message. These are used to separate mime parts in a message.
return "Part." + Convert.ToString(new Random(~unchecked((int)DateTime.Now.AddDays(2).Ticks)).Next()) + "." + Convert.ToString(new Random(unchecked((int)DateTime.Now.AddDays(1).Ticks)).Next());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -