Blogs

Create an e-mail attachment by retrieving from the network

During an implementation of an existing project I have had to add a feature to send an e-mail with attachment that has to be a report of reporting services.

The chosen format is pdf so you need to get the parameters to be passed via url querystring to export the report in pdf format.

I have chosen to download the pdf file, and then I have attached them to the email on the fly without saving it to db or in temporary folders.

Obviously, the information that can be parameterized I have put in the web.config (email from, smtp server and port). Other elements like email to, subject and body of the message I have got from the page where you press the button to send report.

Initially, I have tried to save the file into a MemoryStream object, but when it arrived by email, the file was corrupted.
After several attempts I have found this solution that allowed me to send the file via e-mail correctly.


var mail = new MailMessage(
WebConfigurationManager.AppSettings["EmailScheduledSender"],
Input.Destination,
Input.Subject,
Input.Body
);
var url = GetReportUrl(Input.ScheduledReportId, out filename);
var wc = new WebClient {UseDefaultCredentials = true};
var stream = wc.OpenRead(url);
if (stream != null)
{
var attachment = new Attachment(stream, filename);
mail.Attachments.Add(attachment);
}
var smtpServer = new SmtpClient(WebConfigurationManager.AppSettings["EmailScheduledSmtp"]){
Port = int.Parse(WebConfigurationManager.AppSettings["EmailScheduledPort"])
};
smtpServer.Send(mail);

0


Add a Comment