如何把我的pdf邮件附件
本文关键字:pdf 我的 | 更新日期: 2023-09-27 18:15:07
我需要一个代码的帮助,使我的。pdf文件的附件电子邮件。我试图找到一个解决方案,但我找不到。对不起,我的英语不好
这是我的pdf创建代码
SaveFileDialog dialog1 = new SaveFileDialog();
dialog1.Title = "Saving pdf ";
dialog1.Filter = "PDF Files (*.pdf)|*.pdf|All files (*.*)|*.*";
dialog1.RestoreDirectory = true;
if (dialog1.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(dialog1.FileName);
}
/* DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string caminho = folderBrowserDialog1.SelectedPath;
var pasta2 = caminho.Replace(@"'", @"''");*/
Document doc = new Document(PageSize.A4.Rotate(), 10, 10, 42, 35);
PdfWriter writertest = PdfWriter.GetInstance(doc, new FileStream(dialog1.FileName, FileMode.Create));
doc.Open();
PdfPTable table = new PdfPTable(itemDataGridView.Columns.Count);
for (int j = 0; j < itemDataGridView.Columns.Count; j++)
{
table.AddCell(new Phrase(itemDataGridView.Columns[j].HeaderText));
}
table.HeaderRows = 1;
for (int i = 0; i < itemDataGridView.Rows.Count; i++)
{
for (int k = 0; k < itemDataGridView.Columns.Count; k++)
{
if (itemDataGridView[k, i].Value != null)
{
table.AddCell(new Phrase(itemDataGridView[k, i].Value.ToString()));
}
}
}
doc.Add(table);
doc.Close();
这是我的电子邮件发送代码
Pesquisar_Items pesquisar = new Pesquisar_Items();
var client = new SmtpClient("smtp.live.com", 25);
client.EnableSsl = true;
client.Credentials = new NetworkCredential("josepedrobrito@hotmail.com", "*******");
var mail = new MailMessage();
mail.From = new MailAddress("josepedrobrito@hotmail.com");
mail.To.Add(textBox1.Text);
mail.IsBodyHtml = true;
mail.Subject = textBox2.Text;
string mailBody = "<table width='100%' style='border:Solid 1px Black;'>"; ;
foreach (DataGridViewRow row in itemDataGridView.Rows)
{
mailBody += "<tr>";
foreach (DataGridViewCell cell in row.Cells)
{
mailBody += "<td>" + cell.Value + "</td>";
}
mailBody += "</tr>";
}
mailBody += "</table>";
client.Send(mail);
MessageBox.Show("O email send ");
this.Close();
创建一个Attachment
,然后将其添加到Attachments
集合:
// Create the attachment.
Attachment data = new Attachment(file, MediaTypeNames.Application.Pdf);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
file
是您想要附加到电子邮件的文件的路径名,从您的FileSaveDialog
返回。
你可能想做更多的事情,比如添加时间戳信息等,你需要调用
data.Dispose();
在你发送消息之后。
当您从代码创建文件时,您可以将其保存到临时目录,然后在发送电子邮件后从磁盘中删除它,而无需用户看到对话框或输入文件名。
来源您可以通过简单地附加一个内存流直接从内存创建附件:
using (MemoryStream memoryStream = new MemoryStream())
{
PdfWriter writertest = PdfWriter.GetInstance(doc, memoryStream);
// Write contents of Pdf here
// Set the position to the beginning of the stream.
memoryStream.Seek(0, SeekOrigin.Begin);
// Create attachment
ContentType contentType = new ContentType();
contentType.MediaType = MediaTypeNames.Application.Pdf;
contentType.Name = fileNameTextBox.Text;
Attachment attachment = new Attachment(memoryStream, contentType);
// Add the attachment
message.Attachments.Add(attachment);
// Send Mail via SmtpClient
smtpClient.Send(message);
}
源