ASP.NET发送带有EXCEL附件的电子邮件 [英] asp.net send email with excel attachement
本文介绍了ASP.NET发送带有EXCEL附件的电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是用于创建Excel文件的。
DataTable dt = new DataTable("Grid");
dt.Columns.AddRange(new DataColumn[4] { new DataColumn("H_Id"),
new DataColumn("H_Name"),
new DataColumn("H_PassNo"),
new DataColumn("H_Pass_Issue"),
});
var marydatas = from MarryData in this._context.MarryData.Take(10)
select MarryData;
foreach (var marryData in marydatas)
{
dt.Rows.Add(marryData.H_Id, marryData.H_Name, marryData.H_PassNo, marryData.H_Pass_Issue);}
byte[] bytes = null;
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
bytes = stream.ToArray();
}
}
这是用来发送电子邮件的
var message = new MimeMessage();
message.From.Add(new MailboxAddress("test project", "maazonuae@gmail.com"));
message.To.Add(new MailboxAddress("naren", "a.saaeed81@gmail.com"));
message.Subject = "test maazon";
message.Body = new TextPart("HTML Table Exported Excel Attachment")
{
Text = "hello"
};
var builder = new BodyBuilder();
builder.Attachments.Add("Customers.xlsx", new MemoryStream(bytes));
var body = builder.ToMessageBody();
var emailBody = new MimeKit.BodyBuilder
{
};
emailBody.Attachments.Add("Customers.xlsx", bytes);
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("maazonuae@gmail.com", "maazonuae2021");
client.Send(message);
client.Disconnect(true);
}
因此,当它运行时,只发送不带附件的电子邮件,并以附件形式发送(Text=";Hello";),而不是正文消息。
谢谢
推荐答案
我找到解决方案
var message = new MimeMessage();
message.From.Add(new MailboxAddress(Joey", "joey@friends.com));
message.To.Add(new MailboxAddress("Alice", "alice@wonderland.com"));
message.Subject = "How you doin?";
var builder = new BodyBuilder();
// Set the plain-text version of the message text
builder.TextBody = @"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday. I was hoping you could make it.
Will you be my +1?
-- Joey
";
builder.Attachments.Add("myFile.xlsx", bytes);
// Now we just need to set the message body and we're done
message.Body = builder.ToMessageBody();
////////////////////////////////////////////////////////////
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("maazonuae@gmail.com", "maazonuae2021");
client.Send(message);
client.Disconnect(true);
}
这篇关于ASP.NET发送带有EXCEL附件的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文