git_bsmd/nsw/Source/bsmd.ReportGenerator/BSMDMail.cs
Daniel Schick f4b3d3caf0 Stand nach Live-Schaltung (noch keine Übermittlung Richtung DBH/Dakosy)
Aktiv ist Herberg FormService und der Report Generator
30.Mai 2015
2015-05-30 18:56:16 +00:00

92 lines
3.5 KiB
C#

//
// 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);
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";
foreach (string recipient in Properties.Settings.Default.Recipient)
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.Info("Email sending successful.");
}
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);
}
smtpClient.Dispose();
message.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);
*/
}
}
}