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)