// // Class: Mail // Current CLR: 4.0.30319.34209 // System: Microsoft Visual Studio 10.0 // Author: dani // Created: 5/28/2015 10:24:12 AM // // Copyright (c) 2015 Informatikbüro Daniel Schick. All rights reserved. using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Mime; using System.Net.Mail; using log4net; using bsmd.database; namespace bsmd.ReportGenerator { public class BSMDMail { public static void SendNSWReportAsAttachment(MessageCore core, string filename) { ILog log = LogManager.GetLogger(typeof(BSMDMail)); SmtpClient smtpClient = new SmtpClient(); NetworkCredential basicCredential = new NetworkCredential(Properties.Settings.Default.SMTPUser, Properties.Settings.Default.SMTPPassword); foreach (string recipient in Properties.Settings.Default.Recipient) { MailMessage message = new MailMessage(); MailAddress fromAddress = new MailAddress(Properties.Settings.Default.Sender); // setup up the host, increase the timeout to 5 minutes smtpClient.Host = Properties.Settings.Default.SMTPServer; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = basicCredential; smtpClient.Timeout = (60 * 5 * 1000); smtpClient.EnableSsl = true; message.From = fromAddress; message.Subject = string.Format("NSW Message report for {0}", core.IMO); message.IsBodyHtml = false; message.Body = "see attachment"; message.To.Add(recipient); if (filename != null) { Attachment attachment = new Attachment(filename, MediaTypeNames.Application.Octet); ContentDisposition disposition = attachment.ContentDisposition; disposition.CreationDate = File.GetCreationTime(filename); disposition.ModificationDate = File.GetLastWriteTime(filename); disposition.ReadDate = File.GetLastAccessTime(filename); disposition.FileName = Path.GetFileName(filename); disposition.Size = new FileInfo(filename).Length; disposition.DispositionType = DispositionTypeNames.Attachment; message.Attachments.Add(attachment); } // doch nicht asynchron, da nur eine Nachricht gleichzeitig geschickt werden kann und ich so den sync code spare try { smtpClient.Send(message); log.InfoFormat("Email sending to {0} successful.", recipient); } catch (SmtpException smtpException) { log.ErrorFormat("SMTP error while sending e-mail:{0}", smtpException.Message); } catch (Exception ex) { log.ErrorFormat("other error while sending e-mail:{0}", ex.Message); } message.Dispose(); } smtpClient.Dispose(); // http://stackoverflow.com/questions/7276375/what-are-best-practices-for-using-smtpclient-sendasync-and-dispose-under-net-4 // asynchron schicken und wenn's erledigt ist gleich disposen (wichtig!) /* smtpClient.SendCompleted += (s, e) => { smtpClient.Dispose(); message.Dispose(); }; smtpClient.SendAsync(message, null); */ } } }