发送附件的 mail 类

Attachment 类与 MailMessage 类一起使用。所有邮件都包括 Body,它包含邮件的内容。除了正文外,您可能还想发送其他文件。这些作为附件发送并表示为 Attachment 实例。若要将附件添加到邮件中,请将附件添加到 MailMessage..::.Attachments 集合中。附件内容可以是 String、Stream 或文件名。可以使用任何 Attachment 构造函数来指定附件中的内容。附件的 MIME Content-Type 标头信息由 ContentType 属性表示。Content-Type 标头指定媒体类型和子类型以及任何关联的参数。使用 ContentType 获取与附件关联的实例。MIME Content-Disposition 标头由 ContentDisposition 属性表示。Content-Disposition 标头指定附件的表示和文件时间戳。仅当附件是文件时才发送 Content-Disposition 标头。使用 ContentDisposition 属性可获取与附件关联的实例。MIME Content-Transfer-Encoding 标头由 TransferEncoding 属性表示。
		public static void CreateMessageWithAttachment(string server)
		{
			// Specify the file to be attached and sent.
			// This example assumes that a file named Data.xls exists in the
			// current working directory.
			string file = "data.xls";
			// Create a message and set up the recipients.
			MailMessage message = new MailMessage(
			   "[email protected]",
			   "[email protected]",
			   "Quarterly data report.",
			   "See the attached spreadsheet.");

			// Create  the file attachment for this e-mail message.
			Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
			// Add time stamp information for the file.
			ContentDisposition disposition = data.ContentDisposition;
			disposition.CreationDate = System.IO.File.GetCreationTime(file);
			disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
			disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
			// Add the file attachment to this e-mail message.
			message.Attachments.Add(data);
			//Send the message.
			SmtpClient client = new SmtpClient(server);
			// Add credentials if the SMTP server requires them.
			client.Credentials = CredentialCache.DefaultNetworkCredentials;
			client.Send(message);
			// Display the values in the ContentDisposition for the attachment.
			ContentDisposition cd = data.ContentDisposition;
			Console.WriteLine("Content disposition");
			Console.WriteLine(cd.ToString());
			Console.WriteLine("File {0}", cd.FileName);
			Console.WriteLine("Size {0}", cd.Size);
			Console.WriteLine("Creation {0}", cd.CreationDate);
			Console.WriteLine("Modification {0}", cd.ModificationDate);
			Console.WriteLine("Read {0}", cd.ReadDate);
			Console.WriteLine("Inline {0}", cd.Inline);
			Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
			foreach (DictionaryEntry d in cd.Parameters)
			{
				Console.WriteLine("{0} = {1}", d.Key, d.Value);
			}
			data.Dispose();
		}

你可能感兴趣的:(发送附件的 mail 类)