Sou*_*tyr 2 c# asp.net email-attachments winnovative
我可以发送电子邮件,但我无法创建有效的附件()以放入我的电子邮件.我在网上找到的所有例子都假设它以某种方式保存在我的机器本地并通过路径链接它但事实并非如此.在我的方法中,我使用Winnovative创建文件,然后我想将它附加到电子邮件并发送它.不涉及储蓄.
protected void SendEmail_BtnClick(object sender, EventArgs a)
{
if(IsValidEmail(EmailTextBox.Text))
{
try
{
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(EmailTextBox.Text);
mailMessage.From = new MailAddress("my email");
mailMessage.Subject = " Your Order";
string htmlstring = GenerateHTMLString();
Document pdfDocument = GeneratePDFReport(htmlstring);
//Attachment attachment = new Attachment("Receipt.pdf",pdfDocument);
//mailMessage.Attachments.Add();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
//needs to change this password
smtpClient.Credentials = new NetworkCredential("j@gmail.com","password"); //change password to password of email
smtpClient.EnableSsl = true;
try
{
smtpClient.Send(mailMessage);
EmailErrorMessage("Email Sent");
}
catch(Exception exc)
{
EmailErrorMessage("Email could not be sent");
}
}
catch (Exception ex)
{
EmailErrorMessage("Could not send the e-mail. Error: "+ex.Message);
}
}
else
{
EmailErrorMessage("Please input a valid email.");
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:这是我完成的解决方案.
MailMessage mailMessage = CreateMailMessage();
SmtpClient smtpClient = CreateSMTPClient();
string htmlstring = GenerateHTMLString();
Document pdfDocument = GeneratePDFReport(htmlstring);
// Save the document to a byte buffer
byte[] pdfBytes;
using (var ms = new MemoryStream())
{
pdfDocument.Save(ms);
pdfBytes = ms.ToArray();
}
smtpClient.Send(mailMessage);
EmailErrorMessage("Email Sent");
// create the attachment
Attachment attach;
using (var ms = new MemoryStream(pdfBytes))
{
attach = new Attachment(ms, "application.pdf");
mailMessage.Attachments.Add(attach);
try
{
smtpClient.Send(mailMessage);
EmailErrorMessage("Email Sent");
}
catch (Exception exc)
{
EmailErrorMessage("Could not send the e-mail properly. Error: " + exc.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
结果:电子邮件发送,但附件名为application_pdf而不是application.pdf.有没有什么办法解决这一问题?
我没有使用过Winnovate的PDF,但是快速查看他们的文档表明以下内容应该有效:
// Save the document to a byte buffer
byte[] pdfBytes;
using (var ms = new MemoryStream())
{
pdfDocument.Save(ms);
pdfBytes = ms.ToArray();
}
// create the attachment
Attachment attach;
using (var ms = new MemoryStream(pdfBytes))
{
attach = new Attachment(ms, "application/pdf");
}
// and add it to the message
mailMessage.Attachments.Add(attach);
Run Code Online (Sandbox Code Playgroud)
如果可能是流必须保持打开以便发送消息.也许使用它来添加附件并发送消息:
Attachment attach;
var attachStream = new MemoryStream(pdfBytes);
try
{
attachStream = new Attachment(ms, "application/pdf");
mailMessage.Attachments.Add(attachStream);
// do other stuff to message
// ...
// and then send it.
smtpClient.Send(MailMessage)
}
finally
{
attachStream.Close();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3444 次 |
| 最近记录: |