Spire.Email组件支持在新建邮件时添加附件到邮件信息, 以及提取和删除已有邮件中的附件。本文将以SMTP为例介绍如何使用Spire.Email 添加、提取和删除邮件附件。
添加附件
C#
//实例化一个MailMessage对象,指定发件人邮箱、邮件接收者的邮箱地址
MailAddress addressFrom = "daisy.zhang @e-iceblue.com";
MailAddress addressTo = "LeonDavisLD @outlook.com";
MailMessage message = new MailMessage(addressFrom, addressTo);
//添加邮件标题,正文内容和时间
message.Subject = "Have a Nice Holiday";
message.BodyText = "祝大家双节快乐!";
message.Date = DateTime.Now;
//添加图片和文本附件
message.Attachments.Add(new Attachment("Rose.jpg"));
message.Attachments.Add(new Attachment("Test.txt"));
//保存邮件
message.Save("Sample.msg", MailMessageFormat.Msg);
VB.NET
'实例化一个MailMessage对象,指定发件人邮箱、邮件接收者的邮箱地址
Dim addressFrom As MailAddress = "daisy.zhang @e-iceblue.com"
Dim addressTo As MailAddress = "LeonDavisLD @outlook.com"
Dim message As New MailMessage(addressFrom, addressTo)
'添加邮件标题,正文内容和时间
message.Subject = "Have a Nice Holiday"
message.BodyText = "祝大家双节快乐!"
message.[Date] = DateTime.Now
'添加图片和文本附件
message.Attachments.Add(New Attachment("Rose.jpg"))
message.Attachments.Add(New Attachment("Test.txt"))
'保存邮件
message.Save("Sample.msg", MailMessageFormat.Msg)
提取附件
C#
//加载含有附件的邮件
MailMessage mail = MailMessage.Load("Sample.msg");
//创建一个文件夹并命名为Attachments
if (!Directory.Exists("Attachments"))
{
Directory.CreateDirectory("Attachments");
}
foreach (Attachment attach in mail.Attachments)
{
//获取并保存附件
string filePath = string.Format("Attachments\\{0}", attach.ContentType.Name);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
FileStream fs = File.Create(filePath);
attach.Data.CopyTo(fs);
}
VB.NET
'加载含有附件的邮件
Dim mail As MailMessage = MailMessage.Load("Sample.msg")
'创建一个文件夹并命名为Attachments
If Not Directory.Exists("Attachments") Then
Directory.CreateDirectory("Attachments")
End If
For Each attach As Attachment In mail.Attachments
'获取并保存附件
Dim filePath As String = String.Format("Attachments\{0}", attach.ContentType.Name)
If File.Exists(filePath) Then
File.Delete(filePath)
End If
Dim fs As FileStream = File.Create(filePath)
attach.Data.CopyTo(fs)
Next
删除附件
C#
//加载含有附件的邮件
MailMessage mail = MailMessage.Load("Sample.msg");
// 按顺序删除第一个附件
mail.Attachments.RemoveAt(0);
// 按附件名称删除名为Test.txt的附件
for (int i = 0; i < mail.Attachments.Count; i++)
{
Attachment attach = mail.Attachments[i];
if (attach.ContentType.Name == "Test.txt")
{
mail.Attachments.Remove(attach);
}
}
//保存邮件
mail.Save("HasDeletedAttachment.msg", MailMessageFormat.Msg);
VB.NET
'加载含有附件的邮件
Dim mail As MailMessage = MailMessage.Load("Sample.msg")
' 按顺序删除第一个附件
mail.Attachments.RemoveAt(0)
' 按附件名称删除名为Test.txt的附件
For i As Integer = 0 To mail.Attachments.Count - 1
Dim attach As Attachment = mail.Attachments(i)
If attach.ContentType.Name = "Test.txt" Then
mail.Attachments.Remove(attach)
End If
Next
'保存邮件
mail.Save("HasDeletedAttachment.msg", MailMessageFormat.Msg)