我可以发送电子邮件和所有内容,但我无法创建有效的 Attachment() 来放入我的电子邮件。我在网上找到的所有示例都假定它以某种方式保存在我的机器上本地并通过路径链接它,但事实并非如此。在我的方法中,我使用 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.");
}
}
编辑:这是我完成的解决方案。
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);
}
}
结果:电子邮件发送,但附件名为 application_pdf 而不是 application.pdf。有没有什么办法解决这一问题?