Esempio n. 1
0
        /// <summary>
        /// Sends email with attachment
        /// </summary>
        /// <param name="mailBody">email body</param>
        /// <param name="mailSubject">email subject</param>
        /// <param name="emailsString">email addresses</param>
        /// <param name="attachmentPaths">paths to attached files</param>
        /// <returns>return true if email was sended</returns>
        public static bool SendEmail(string mailBody, string mailSubject, string emailsString,
                                     params string[] attachmentPaths)
        {
            ILog log = LogManager.GetLogger(AppSettings.GetCommonLoggerName());

            try
            {
                SmtpClient client = new SmtpClient(AppSettings.GetEmailServerName());

                List <string> addresses = new List <string>();
                ParseEmailsString(emailsString, addresses);

                if (addresses.Count == 0)
                {
                    return(false);
                }

                using (MailMessage message = new MailMessage(AppSettings.GetEmailFromAddress(), addresses[0]))
                {
                    for (int i = 1; i < addresses.Count; ++i)
                    {
                        message.To.Add(addresses[i]);
                    }

                    message.Body    = mailBody;
                    message.Subject = mailSubject;

                    foreach (string str in attachmentPaths)
                    {
                        if (File.Exists(str))
                        {
                            message.Attachments.Add(new Attachment(str));
                        }
                        else
                        {
                            log.Info("File " + str + " does not exist");
                        }
                    }

                    client.UseDefaultCredentials = false;
                    NetworkCredential theCredential = new NetworkCredential(
                        AppSettings.GetEmailClientLogin(), AppSettings.GetEmailClientPassword());
                    client.Credentials = theCredential;

                    log.Info("SendEmail: sending email to: " + emailsString);
                    client.Send(message);
                }
            }
            catch (FormatException e)
            {
                log.Error("SendEmail", e);
                return(false);
            }
            catch (ArgumentException e)
            {
                log.Error("SendEmail", e);
                return(false);
            }
            catch (InvalidOperationException e)
            {
                log.Error("SendEmail", e);
                return(false);
            }
            catch (SmtpException e)
            {
                log.Error("SendEmail", e);
                return(false);
            }

            return(true);
        }