I can send an email and everything but I cannot create a valid Attachment() to put into my email. All examples I've found online assumes that it is somehow saved locally on my machine and links it via path but that is not the case. In my method, I create the file using Winnovative, and then I want to attach it to the e-mail and send it. No saving involved.
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.");
}
}
EDIT: This is my finished solution.
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);
}
}
Result: The email sends, but the attachment is named application_pdf instead of application.pdf. Is there any way to fix this?