Esempio n. 1
0
        public bool SendEmail(string subject, IList<string> userList, IList<string> ccList, string body, MailPriority priority = MailPriority.Normal)
        {
            var mail = new MailMessage
              {
            From = fromAddress,
            Subject = subject,
            Body = body,
            BodyEncoding = Encoding.UTF8,
            IsBodyHtml = true,
            Priority = priority
              };

              foreach (var user in userList)
            mail.To.Add(user);
              foreach (var cc in ccList)
            mail.CC.Add(cc);

              var client = new SmtpClient
              {
            Host = host,
            UseDefaultCredentials = false,
            Credentials = new System.Net.NetworkCredential(userName, password),
            DeliveryMethod = SmtpDeliveryMethod.Network
              };
              try
              {
            client.Send(mail);
            return true;
              }
              catch
              {
            return false;
              }
        }
Esempio n. 2
0
 public EmailTemplate(XmlNode rootNode)
 {
     XmlNode namedItem = rootNode.Attributes.GetNamedItem("priority");
     MailPriority mailPriority;
     if (namedItem != null && System.Enum.TryParse<MailPriority>(namedItem.InnerText, out mailPriority))
     {
         this.priority = mailPriority;
     }
     namedItem = rootNode.Attributes.GetNamedItem("templateName");
     if (namedItem != null)
     {
         this.templateName = namedItem.InnerText;
     }
     XmlNode xmlNode = rootNode.SelectSingleNode("subject");
     if (xmlNode != null)
     {
         this.subject = xmlNode.InnerText;
     }
     XmlNode xmlNode2 = rootNode.SelectSingleNode("from");
     if (xmlNode2 != null)
     {
         this.From = xmlNode2.InnerText;
     }
     XmlNode xmlNode3 = rootNode.SelectSingleNode("body");
     if (xmlNode3 != null)
     {
         namedItem = xmlNode3.Attributes.GetNamedItem("url");
         if (namedItem != null)
         {
             this.BodyUrl = namedItem.InnerText;
             return;
         }
         this.Body = xmlNode3.InnerXml;
     }
 }
Esempio n. 3
0
        public SendBulkEmail( ArrayList recipients, string priority, string format, string portalAlias )
        {
            this.Recipients = recipients;
            switch( priority )
            {
                case "1":

                    this.Priority = MailPriority.High;
                    break;
                case "2":

                    this.Priority = MailPriority.Normal;
                    break;
                case "3":

                    this.Priority = MailPriority.Low;
                    break;
            }
            if( format == "BASIC" )
            {
                this.BodyFormat = MailFormat.Text;
            }
            else
            {
                this.BodyFormat = MailFormat.Html;
                // Add Base Href for any images inserted in to the email.
                this.Body = "<Base Href='" + portalAlias + "'>";
            }
        }
Esempio n. 4
0
File: Mail.cs Progetto: kLeZ/Gecko
        private static MailMessage SetBasicInfos(string MessageFrom, string MessageTo, string MessageCc, string MessageBcc, string MessageSubject, MailPriority MessagePriority, string MessageText)
        {
            char[] delim = { ',', ';', ' ', ':', '\\', '|' };
            StringSplitOptions opt = StringSplitOptions.RemoveEmptyEntries;
            MailMessage myMail = new MailMessage();

            myMail.From = new MailAddress(MessageFrom);
            myMail.To.AddList(MessageTo.Split(delim, opt).Encapsulate<string, MailAddress>());

            if (!String.IsNullOrEmpty(MessageCc))
                myMail.CC.AddList<MailAddress>(
                    MessageCc.Split(delim, opt)
                    .Encapsulate<string, MailAddress>()
                    );

            if (!String.IsNullOrEmpty(MessageBcc))
                myMail.Bcc.AddList<MailAddress>(
                    MessageCc.Split(delim, opt)
                    .Encapsulate<string, MailAddress>()
                    );

            myMail.Subject = MessageSubject;
            myMail.Priority = MessagePriority;
            myMail.BodyEncoding = Encoding.UTF8;
            myMail.Body = MessageText;
            return myMail;
        }
Esempio n. 5
0
        /// <summary>
        /// Automatically sends email to Report Error Email. CC and BCC are allowed.
        /// </summary>
        /// <param name="subject">Email Subject.</param>
        /// <param name="message">Email Message. It can be HTML.</param>
        /// <param name="priority"> Mail Priority Normal | Low | High</param>
        /// <param name="isHtml">Automatically set as TRUE, change to False for a non html message.</param>
        /// <param name="CC"></param>
        /// <param name="BCC"></param>
        /// <returns></returns>
        public static bool Delivery(string subject, string message, MailPriority priority, bool isHtml = true, string[] CC = null, string[] BCC = null)
        {
            MailMessage mail = new MailMessage();
            SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]);

            try
            {
                mail.To.Add(ConfigurationManager.AppSettings["ReportErrorsEmail"]);
                mail.From = new MailAddress(ConfigurationManager.AppSettings["NoReplyEmail"]);

                mail.Priority = priority;
                mail.IsBodyHtml = isHtml;
                mail.Subject = subject;
                mail.Body = message;

                if (CC != null)
                    foreach (var item in CC)
                        mail.CC.Add(item);

                if (BCC != null)
                    foreach (var item in BCC)
                        mail.Bcc.Add(item);

                smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["smtpUsrEmail"], ConfigurationManager.AppSettings["smtpPwd"]);
                // Use port  as necessary.
                smtp.Port = 587;

                smtp.Send(mail);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
Esempio n. 6
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="smtpClient"></param>
        /// <param name="MailFrom_Address"></param>
        /// <param name="MailTo_Address"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyEncoded"></param>
        /// <param name="IsBodyHtml"></param>
        /// <param name="Priority"></param>
        /// <param name="Attachments">DisposableList<Attachment></param>
        /// <returns></returns>
        public static async Task InviaEmailAsync(SmtpClient smtpClient,
                                     MailAddress MailFrom_Address, string MailsTo,
                                     string Subject, string Body,
                                     bool IsBodyEncoded = false,
                                     bool IsBodyHtml = false,
                                     MailPriority Priority = MailPriority.Normal,
                                     List<Attachment> Attachments = null)
        {
            using (MailMessage mailMsg = new MailMessage())
            {
                mailMsg.From = MailFrom_Address;
                mailMsg.To.Add(MailsTo);

                mailMsg.Subject = Subject;
                string body = Body;
                if (IsBodyEncoded)
                    body = System.Net.WebUtility.HtmlDecode(body);
                mailMsg.Body = body;
                mailMsg.IsBodyHtml = IsBodyHtml;
                mailMsg.Priority = Priority;

                //allegati
                if (Attachments != null && Attachments.Count > 0)
                    foreach (var attach in Attachments)
                        mailMsg.Attachments.Add(attach);

                await smtpClient.SendMailAsync(mailMsg).ConfigureAwait(false);
            }
        }
Esempio n. 7
0
    //function to send email. Returns true if successful, returns false if unsuccessful
    public static bool SendMailMessage(string from, string recipient, string bcc, string cc, string subject, string body, bool isHTML, MailPriority priority)
    {
        try
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(from); //set from address
            string[] arrRecipients = recipient.Split(';'); //add recipients to "TO" field
            foreach (object x in arrRecipients) { msg.To.Add(new MailAddress(x.ToString())); }

            if (bcc != "" && bcc != null) { msg.Bcc.Add(new MailAddress(bcc)); } //set bcc field
            if (cc != "" && cc != null) { msg.CC.Add(new MailAddress(cc)); } //set cc field
            msg.Subject = subject; //set subject field

            if (isHTML == false) { msg.IsBodyHtml = false; } //set HTML option depending on param
            else { msg.IsBodyHtml = true; }

            msg.Body = body; //set body
            msg.Priority = priority; //set message priority

            SmtpClient client = new SmtpClient(); //new SMTP client - settings in web.config
            client.Send(msg); //send message
        }
        catch {return false; }

        return true;
    }
Esempio n. 8
0
        public Message(string subject, string recipientAddress,
		               string htmlBody, string plainTextBody,
		               string senderAddress = "", string senderName = "",
		               MailPriority priority = MailPriority.Normal,
		               string copyAddress = "", string blindCopyAddress = "")
        {
            if(string.IsNullOrEmpty(subject))
                throw new ArgumentOutOfRangeException("subject", "The 'subject' parameter can not be null or empty");

            if(string.IsNullOrEmpty(recipientAddress))
                throw new ArgumentOutOfRangeException("recipientAddress", "The 'recipientAddress' parameter can not be null or empty");

            if(string.IsNullOrEmpty(htmlBody))
                throw new ArgumentOutOfRangeException("htmlBody", "The 'htmlBody' parameter can not be null or empty");

            if(string.IsNullOrEmpty(plainTextBody))
                throw new ArgumentOutOfRangeException("plainTextBody", "The 'plainTextBody' parameter can not be null or empty");

            this._Subject = subject;
            this._RecipientAddress = recipientAddress;
            if(senderAddress != "") this._Sender = new MailAddress(senderAddress, senderName);
            this._HtmlBody = htmlBody;
            this._PlainTextBody = plainTextBody;
            this._Priority = priority;
            this._CopyAddress = copyAddress;
            this._BlindCopyAddress = blindCopyAddress;
        }
Esempio n. 9
0
        /// <summary>
        /// 结合配置文件改的
        /// </summary>
        /// <param name="mail"></param>
        public static bool SendEmail(string from, string displayName, string to0, string subject, string body, string encoding, MailPriority prioity)
        {
            if (string.IsNullOrEmpty(displayName))
                displayName = from;
            MailAddress _from = new MailAddress(from, displayName);

            MailAddress _to = new MailAddress(to0);
            MailMessage mail = new MailMessage(_from, _to);
            mail.Subject = subject;
            mail.Body = body;
            mail.BodyEncoding = System.Text.Encoding.Default;
            if (!string.IsNullOrEmpty(encoding))
            {
                mail.BodyEncoding = System.Text.Encoding.GetEncoding(encoding);
            }
            mail.IsBodyHtml = true;
            mail.Priority = prioity;

            Configs.Config cfg = new Configs.Config();
            // Override To
            if (!string.IsNullOrEmpty(cfg.Email.MailTo_Override))
            {
                var tos = cfg.Email.MailTo_Override.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                mail.To.Clear();
                foreach (var to in tos)
                {
                    mail.To.Add(to);
                }
            }
            return SendEmail(mail);
        }
Esempio n. 10
0
        /// <summary>
        /// Sends and email
        /// </summary>
        /// <param name="to">Message to address</param>
        /// <param name="body">Text of message to send</param>
        /// <param name="subject">Subject line of message</param>
        /// <param name="fromAddress">Message from address</param>
        /// <param name="fromDisplay">Display name for "message from address"</param>
        /// <param name="credentialUser">User whose credentials are used for message send</param>
        /// <param name="credentialPassword">User password used for message send</param>
        /// <param name="attachments">Optional attachments for message</param>
        public static void Email(string mailServerAddress,
                                 string toAddress,
                                 string body,
                                 string subject,
                                 string fromAddress,
                                 string fromDisplay,
                                 string credentialUser,
                                 string credentialPassword,
                                 MailAttachment[] attachments,
                                 string linkConfirm = null,
                                 string passPlainText = null,
                                 MailType mailType = MailType.Normal,
                                 MailPriority mailpriority = MailPriority.Normal)
        {
            string host = mailServerAddress;
            body = UpgradeEmailFormat(body, linkConfirm, passPlainText, mailType);
            try
            {
                MailMessage mail = new MailMessage() { Body = body, IsBodyHtml = true };

                string[] toArray = toAddress.Split(';');

                foreach (string to in toArray)
                {
                    mail.To.Add(new MailAddress(to.Trim()));
                }

                mail.From = new MailAddress(fromAddress, fromDisplay, Encoding.UTF8);
                mail.Subject = subject;
                mail.SubjectEncoding = Encoding.UTF8;
                mail.Priority = mailpriority;

                using (SmtpClient smtp = new SmtpClient())
                {

                    // This is necessary for gmail
                    //smtp.EnableSsl = true;
                    //smtp.Credentials = new System.Net.NetworkCredential(credentialUser, credentialPassword);

                    smtp.Host = host;
                    smtp.Send(mail);
                }
            }
            catch
            {
                StringBuilder sb = new StringBuilder(1024);
                sb.Append("\\nTo:" + toAddress);
                sb.Append("\\nbody:" + body);
                sb.Append("\\nsubject:" + subject);
                sb.Append("\\nfromAddress:" + fromAddress);
                sb.Append("\\nfromDisplay:" + fromDisplay);
                sb.Append("\\ncredentialUser:"******"\\ncredentialPasswordto:" + credentialPassword);
                sb.Append("\\nHosting:" + host);
                Debug.Print(sb.ToString());
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Sends the template mail.
        /// </summary>
        /// <param name="mailSettings">STMP email settings</param>
        /// <param name="fromAddress">From address.</param>
        /// <param name="fromDisplayName">From display name.</param>
        /// <param name="toAddress">To address.</param>
        /// <param name="toName">To display name.</param>
        /// <param name="ccAddressesCSV">Optional CC addresses (CSV).</param>
        /// <param name="bccAddressesCSV">Optional BCC addresses CSV.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="templateFilePath">The template file path.</param>
        /// <param name="replacements">The replacements.</param>
        /// <param name="appRootFolder">'/' if site is running in the base folder, or '/foldername/' if site is running in a sub-folder.</param>
        /// <param name="templateVirtualFolder">The template virtual folder.</param>
        /// <param name="wrapperTemplateFilePath">Optional wrapper template file path.</param>
        /// <param name="isBodyHtml">Set to true if the body of the email is HTML; false otherwise.</param>
        public static void SendTemplateMail(MailSettings mailSettings, string toAddress, string toName,
			string ccAddressesCSV, string bccAddressesCSV, string subject, string templateFilePath,
			ListDictionary replacements, string templateVirtualFolder, string appRootFolder, string wrapperTemplateFilePath = null, bool isBodyHtml = true, MailPriority priority = MailPriority.Normal,
			string attachmentDosPaths = null)
        {
            if (File.Exists(templateFilePath))
            {
                StringBuilder messageText = null;
                string templateText = null;

                if (File.Exists(templateFilePath))
                {
                    templateText = File.ReadAllText(templateFilePath);
                }
                else
                {
                    throw new Exception("Cannot find template " + templateFilePath);
                }

                if (!string.IsNullOrEmpty(wrapperTemplateFilePath) && File.Exists(wrapperTemplateFilePath))
                {
                    string str = File.ReadAllText(wrapperTemplateFilePath).Replace("@@WrapperContents", templateText);
                    messageText = new StringBuilder(str);
                }
                else
                {
                    messageText = new StringBuilder(templateText);
                }

                // Add some mandatory fields to the replacements
                if (replacements == null)
                {
                    // Ensure not null.
                    replacements = new ListDictionary();
                }

                replacements.Add("@@HttpRoot", string.Format("http://{0}/", mailSettings.Host));
                replacements.Add("@@TemplateFolder", string.Format("http://{0}{1}{2}", mailSettings.Host, appRootFolder, templateVirtualFolder.Trim("~/".ToCharArray())));

                SendMail(
                    mailSettings,
                    toAddress,
                    toName,
                    ccAddressesCSV,
                    bccAddressesCSV,
                    subject,
                    messageText.ToString(),
                    true,
                    attachmentDosPaths,
                    priority,
                    replacements);
            }
            else
            {
                //Every1.Core.Web.Utils.TraceWarn("SendTemplateMail", "templateFilePath " + templateFilePath + " does not exist");
            }
        }
Esempio n. 12
0
        public void SendEmail(string subject, string body, string mailTo, string replayTo, MailPriority mailPriority)
        {
            //SendMailExchange(mailTo, subject, body, replayTo);

            string SMTPEmailHost = systemMgr.GetEntityPreferenceValue(Entity.SYS.EntityPreference.CodeEnum.SMTPEmailHost);
            string SMTPEmailPasswd = systemMgr.GetEntityPreferenceValue(Entity.SYS.EntityPreference.CodeEnum.SMTPEmailPasswd);
            string emailFrom = systemMgr.GetEntityPreferenceValue(Entity.SYS.EntityPreference.CodeEnum.SMTPEmailAddr);

            SMTPHelper.SendSMTPEMail(subject, body, emailFrom, mailTo, SMTPEmailHost, SMTPEmailPasswd, (!string.IsNullOrWhiteSpace(replayTo) ? replayTo : emailFrom), mailPriority);

        }
Esempio n. 13
0
 public Boolean SendEmail(String toAddress, String addresseName, String from, String senderName, String subject, String msgBody, MailPriority msgPriority)
 {
     try
     {
         return SendEmail(toAddress, addresseName, String.Empty, String.Empty, from, senderName, subject, msgBody, true, msgPriority);
     }
     catch
     {
         return false;
     }
 }
Esempio n. 14
0
 public static bool SendEmailByCredential(string host, MailPriority priority, string user_name, string password, string[] mailto, string[] cc, string[] bcc, string subject, string body, bool is_body_html, string[] attachments, bool enableSSL, System.Collections.Specialized.NameValueCollection messageHeaders, string reply_to)
 {
     SmtpClient mail = new SmtpClient();
     mail.DeliveryMethod = SmtpDeliveryMethod.Network;
     mail.Host = host;// "smtp.163.com";
     mail.UseDefaultCredentials = false;
     mail.Credentials = new System.Net.NetworkCredential(user_name, password);
     mail.EnableSsl = enableSSL;
     MailMessage message = new MailMessage();
     if (messageHeaders != null && messageHeaders.Count > 0)
     {
         message.Headers.Add(messageHeaders);
     }
     message.From = new MailAddress(user_name + "@" + host.Substring(host.IndexOf(".") + 1));
     if (mailto != null)
     {
         foreach (string s in mailto)
         {
             if (!string.IsNullOrEmpty(s))
                 message.To.Add(s);
         }
     }
     if (cc != null)
     {
         foreach (string s in cc)
         {
             if (!string.IsNullOrEmpty(s))
                 message.CC.Add(s);
         }
     }
     if (bcc != null)
     {
         foreach (string s in bcc)
         {
             if (!string.IsNullOrEmpty(s))
                 message.Bcc.Add(s);
         }
     }
     if (!string.IsNullOrEmpty(reply_to)) message.ReplyTo = new MailAddress(reply_to);
     message.Subject = subject;
     message.Body = body;
     message.BodyEncoding = System.Text.Encoding.UTF8;
     message.IsBodyHtml = is_body_html;
     message.Priority = priority;
     if (attachments != null)
     {
         foreach (string s in attachments)
         {
             message.Attachments.Add(new Attachment(s));
         }
     }
     mail.Send(message);
     return true;
 }
Esempio n. 15
0
        public static async Task Send(string to, string body, string subject, bool? isHtml = null, MailPriority priority = MailPriority.Normal)
        {
            MailMessage email = new MailMessage(new MailAddress(ConfigurationManager.AppSettings["EmailFrom"]), new MailAddress(to));

            email.Subject = subject;
            email.Body = body;
            email.BodyEncoding = System.Text.Encoding.Default;
            email.Priority = priority;
            email.IsBodyHtml = (isHtml.HasValue ? isHtml.Value : true);

            await smtpClient.SendMailAsync(email);
        }
Esempio n. 16
0
File: Mail.cs Progetto: kLeZ/Gecko
        /// <summary>
        /// Invia un messaggio di posta elettronica
        /// </summary>
        /// <param name="MessageFrom">Mittente</param>
        /// <param name="MessageTo">Destinatario o destinatari</param>
        /// <param name="MessageCc">Destinatario o destinatari in copia conoscenza</param>
        /// <param name="MessageBcc">Destinatario o destinatari in copia conoscenza nascosta</param>
        /// <param name="MessageSubject">Soggetto del messaggio</param>
        /// <param name="MessagePriority">Priorità del messaggio</param>
        /// <param name="MessageText">Testo del messaggio</param>
        /// <param name="ServerName">Server di email</param>
        public static void SendMail(string MessageFrom, string MessageTo, string MessageCc, string MessageBcc, string MessageSubject, MailPriority MessagePriority, string MessageText, string ServerName, bool EnableSsl, NetworkCredential authentication)
        {
            MailMessage myMail = SetBasicInfos(MessageFrom, MessageTo, MessageCc, MessageBcc, MessageSubject, MessagePriority, MessageText);
            SmtpClient mySmtpC = null;
            if (ServerName != null)
                mySmtpC = new SmtpClient(ServerName);
            else
                mySmtpC = new SmtpClient();

            mySmtpC.EnableSsl = EnableSsl;
            if (authentication != null)
                mySmtpC.Credentials = authentication;
            mySmtpC.Send(myMail);
        }
Esempio n. 17
0
        public void Send(MessageRoutingSystemError message, bool isPool = false, MailPriority priority = MailPriority.Normal)
        {
            try
            {
                var body = GenerateHtml(message, isPool);

                using (var mailMessage = new MailMessage())
                {
                    mailMessage.From = new MailAddress(FromAddress);

                    // Add recipients
                    if (!string.IsNullOrWhiteSpace(ToAddress))
                    {
                        ToAddress.Split(';').ToList().ForEach(x => mailMessage.To.Add(x));
                    }
                    else
                    {
                        var defaultDelivery = ConfigurationManager.AppSettings["DefaultDelivery"];
                        defaultDelivery.Split(';').ToList().ForEach(x => mailMessage.To.Add(x));
                    }

                    mailMessage.Priority = priority;
                    mailMessage.Body = body;
                    mailMessage.IsBodyHtml = true;
                    mailMessage.Subject = string.IsNullOrWhiteSpace(Subject) ? $"Error Occurred in Application '{message.ApplicationName}'" : Subject;

                    var smtpClient = new SmtpClient()
                    {
                        Host = Host,
                        Port = Port,
                        UseDefaultCredentials = false,
                        EnableSsl = true
                    };

                    var networkCredentials = new NetworkCredential
                    {
                        UserName = Username,
                        Password = Password
                    };

                    smtpClient.Credentials = networkCredentials;
                    smtpClient.Send(mailMessage);
                }
            }
            catch (Exception e)
            {

            }
        }
 public Task SendEmailAsync(string toAddress, string subject, string message, MailPriority priority = MailPriority.Normal)
 {
     var mail = new MailMessage(ConfigurationManager.AppSettings["EmailFromAddress"], toAddress);
     var client = new SmtpClient();
     client.Port = 25;
     client.DeliveryMethod = SmtpDeliveryMethod.Network;
     client.UseDefaultCredentials = false;
     client.Host = ConfigurationManager.AppSettings["EmailHost"];
     mail.IsBodyHtml = true;
     mail.Subject = subject;
     mail.Body = message;
     mail.Priority = priority;
     client.SendAsync(mail, null);
     return Task.FromResult(0);
 }
Esempio n. 19
0
 public void SendEmail(string subject, string body, string mailTo, string replayTo, MailPriority mailPriority)
 {
     //string SMTPEmailHost = systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.SMTPEmailHost);
     //string SMTPEmailPasswd = systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.SMTPEmailPasswd);
     //string emailFrom = systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.SMTPEmailAddr);
     string SendMailServiceAddress = systemMgr.GetEntityPreferenceValue(com.Sconit.Entity.SYS.EntityPreference.CodeEnum.SendMailServiceAddress);
     string SendMailServicePort = systemMgr.GetEntityPreferenceValue(com.Sconit.Entity.SYS.EntityPreference.CodeEnum.SendMailServicePort);
     SendMail.SendMailV2 sendMailv2 = new SendMail.SendMailV2();
     sendMailv2.Url = ServiceURLHelper.ReplaceServiceUrl(sendMailv2.Url, SendMailServiceAddress, SendMailServicePort);
     SendMail.SecurityHeader securityHeader = new SendMail.SecurityHeader();
     securityHeader.UserName = userName;
     securityHeader.UserPassword = userPassword;
     sendMailv2.SecurityHeaderValue = securityHeader;
     sendMailv2.SendEmailAndUpAttachments(mailTo, string.Empty, subject, body, new UpAttachments[] { }, isOneByOne, senderNo);
     //SMTPHelper.SendSMTPEMail(subject, body, emailFrom, mailTo, SMTPEmailHost, SMTPEmailPasswd, (!string.IsNullOrWhiteSpace(replayTo) ? replayTo : emailFrom), mailPriority);
 }
Esempio n. 20
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        public void SendMail(string to, string cc, string subject, string body, MailPriority priority, params Guid[] files)
        {
            using (TranscationHelper trans = TranscationHelper.GetInstance())
            {
                trans.BeginTrans();
                try
                {
                    SendMail(trans, to, cc, subject, body, priority, files);

                    trans.CommitTrans();
                }
                catch
                {
                    trans.RollTrans();
                    throw;
                }
            }
        }
Esempio n. 21
0
 public static void Send(string fromAddress, string fromDisplay, List<string> toAddressList, List<string> ccAddressList,
     List<string> bccAddressList, string subject, string body, Encoding charset, bool isBodyHtml = true,
     MailPriority priority = MailPriority.Normal, MailSendType type = MailSendType.Smtp)
 {
     MailEntity entity = new MailEntity
     {
         FromAddress = fromAddress,
         FromDisplay = fromDisplay,
         ToAddressList = toAddressList,
         CcAddressList = ccAddressList,
         BccAddressList = bccAddressList,
         Subject =subject,
         Body = body,
         Charset = charset,
         IsBodyHtml = isBodyHtml,
         Priority = priority
     };
     Send(entity, type);
 }
        ///
        /// Creates a new serializeable mailmessage based on a MailMessage object
        ///
        public SerializeableMailMessage(MailMessage mailMessage)
        {
            IsBodyHtml = mailMessage.IsBodyHtml;
            Body = mailMessage.Body;
            Subject = mailMessage.Subject;
            From = SerializeableMailAddress.GetSerializeableMailAddress(mailMessage.From);
            _to = new List<SerializeableMailAddress>();
            foreach (var mailAddress in mailMessage.To)
            {
                _to.Add(SerializeableMailAddress.GetSerializeableMailAddress(mailAddress));
            }

            _cc = new List<SerializeableMailAddress>();
            foreach (var mailAddress in mailMessage.CC)
            {
                _cc.Add(SerializeableMailAddress.GetSerializeableMailAddress(mailAddress));
            }

            _bcc = new List<SerializeableMailAddress>();
            foreach (var mailAddress in mailMessage.Bcc)
            {
                _bcc.Add(SerializeableMailAddress.GetSerializeableMailAddress(mailAddress));
            }

            _attachments = new List<SerializeableAttachment>();
            foreach (var attachment in mailMessage.Attachments)
            {
                _attachments.Add(SerializeableAttachment.GetSerializeableAttachment(attachment));
            }

            _bodyEncoding = mailMessage.BodyEncoding;

            _deliveryNotificationOptions = mailMessage.DeliveryNotificationOptions;
            _headers = SerializeableCollection.GetSerializeableCollection(mailMessage.Headers);
            _priority = mailMessage.Priority;
            ReplyTo = mailMessage.ReplyToList.Select(SerializeableMailAddress.GetSerializeableMailAddress).ToList();
            Sender = SerializeableMailAddress.GetSerializeableMailAddress(mailMessage.Sender);
            _subjectEncoding = mailMessage.SubjectEncoding;

            foreach (AlternateView av in mailMessage.AlternateViews)
                _alternateViews.Add(SerializeableAlternateView.GetSerializeableAlternateView(av));
        }
Esempio n. 23
0
        /// <summary>
        /// Sends an email on a new thread.
        /// </summary>
        /// <param name="mailSettings">The mailSettings.</param>
        /// <param name="toAddress">To address.</param>
        /// <param name="toName">To name. Optional. Ignored if null or whitespace.</param>
        /// <param name="ccAddressesCsv">Optional CSV of CC addresses.</param>
        /// <param name="bccAddressesCsv">Optional CSV of BCC addresses.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body.</param>
        /// <param name="isBodyHtml">If set to <c>true</c> the body is HTML.</param>
        /// <param name="attachmentDosPaths">Optional full DOS paths to file attachments (semi-colon-separated).</param>
        /// <param name="priority">Priority of the email.</param>
        /// <param name="replacements">Optional dictionary of key-value pairs of replacememts for the email body.</param>
        public static void SendMail(MailSettings mailSettings, string toAddress, string toName, 
			string ccAddressesCsv, string bccAddressesCsv, string subject, string body, bool isBodyHtml, string attachmentDosPaths = null, MailPriority priority = MailPriority.Normal, IDictionary replacements = null)
        {
            var args = new object[] {
                mailSettings,
                toAddress,
                toName,
                ccAddressesCsv,
                bccAddressesCsv,
                subject,
                body,
                isBodyHtml,
                attachmentDosPaths,
                priority,
                replacements
            };

            Thread newThread = new Thread(SendMail);
            newThread.Start(args);
        }
Esempio n. 24
0
        internal static void SendMail(TranscationHelper trans, string to, string cc, string subject, string body, MailPriority priority, params Guid[] files)
        {
            Message message = new Message();
            message.From = Sender.GetDefaultFrom();
            message.To = to;
            message.CC = cc;
            message.Subject = subject;
            message.Body = body;
            message.Priority = priority;

            MessageDa.InsertMaillQueue(message, trans);

            if (files != null)
            {
                foreach (Guid file in files)
                {
                    MessageDa.InsertMaillAttach(file, Utils.SysFileDir(), message.UID, trans);
                }
            }
        }
Esempio n. 25
0
		public static void Send(MailAddress from, MailAddress to, MailAddress bcc, MailAddress cc, string subject, string body, bool isBodyHtml, MailPriority priority)
		{
			var mailMessage = new MailMessage();

			mailMessage.From = from;
			mailMessage.To.Add(to);

			if (bcc != null)
				mailMessage.Bcc.Add(bcc);

			if (cc != null)
				mailMessage.CC.Add(cc);

			mailMessage.Subject = subject;
			mailMessage.Body = body;
			mailMessage.IsBodyHtml = isBodyHtml;
			mailMessage.Priority = priority;

			var mSmtpClient = new SmtpClient();
			mSmtpClient.Send(mailMessage);
		}
Esempio n. 26
0
    /// 
    /// Creates a new serializeable mailmessage based on a MailMessage object
    /// 
    public MailMessageWrapper(MailMessage mm)
    {
      IsBodyHtml = mm.IsBodyHtml;
      Body = mm.Body;
      Subject = mm.Subject;
      From = MailAddressWrapper.GetSerializeableMailAddress(mm.From);
      foreach (MailAddress ma in mm.To)
      {
        To.Add(MailAddressWrapper.GetSerializeableMailAddress(ma));
      }
      foreach (MailAddress ma in mm.CC)
      {
        CC.Add(MailAddressWrapper.GetSerializeableMailAddress(ma));
      }
      foreach (MailAddress ma in mm.Bcc)
      {
        Bcc.Add(MailAddressWrapper.GetSerializeableMailAddress(ma));
      }
      foreach (Attachment att in mm.Attachments)
      {
        Attachments.Add(AttachmentWrapper.GetSerializeableAttachment(att));
      }

      BodyEncoding = mm.BodyEncoding;

      DeliveryNotificationOptions = mm.DeliveryNotificationOptions;
      Headers = CollectionWrapper.GetSerializeableCollection(mm.Headers);
      Priority = mm.Priority;

      foreach (MailAddress ma in mm.ReplyToList)
      {
        ReplyTo.Add(MailAddressWrapper.GetSerializeableMailAddress(ma));
      }

      Sender = MailAddressWrapper.GetSerializeableMailAddress(mm.Sender);
      SubjectEncoding = mm.SubjectEncoding;

      foreach (AlternateView av in mm.AlternateViews)
        AlternateViews.Add(AlternateViewWrapper.GetSerializeableAlternateView(av));
    }
Esempio n. 27
0
        public SerializableMailMessage(MailMessage mailMessage)
        {
            IsBodyHtml = mailMessage.IsBodyHtml;
            Body = mailMessage.Body;
            Subject = mailMessage.Subject;
            From = new SerializableMailAddress(mailMessage.From);

            foreach (MailAddress ma in mailMessage.To)
                To.Add(new SerializableMailAddress(ma));

            foreach (MailAddress ma in mailMessage.CC)
                CC.Add(new SerializableMailAddress(ma));

            foreach (MailAddress ma in mailMessage.Bcc)
                Bcc.Add(new SerializableMailAddress(ma));

            foreach (Attachment att in mailMessage.Attachments)
                Attachments.Add(new SerializableAttachment(att));

            BodyEncoding = mailMessage.BodyEncoding;

            DeliveryNotificationOptions = mailMessage.DeliveryNotificationOptions;
            Headers = new SerializableCollection(mailMessage.Headers);
            Priority = mailMessage.Priority;

            foreach (MailAddress ma in mailMessage.ReplyToList)
                ReplyToList.Add(new SerializableMailAddress(ma));

            if (mailMessage.Sender != null)
                Sender = new SerializableMailAddress(mailMessage.Sender);

            SubjectEncoding = mailMessage.SubjectEncoding;

            foreach (AlternateView av in mailMessage.AlternateViews)
                AlternateViews.Add(new SerializableAlternateView(av));
        }
Esempio n. 28
0
        public static int MailPort           = Convert.ToInt32(ConfigurationManager.AppSettings["MailPort"]);         //端口

        public static void SendMail(List <string> To, List <string> CC, List <string> BCC, string Subject, string Body, MailPriority Priority)
        {
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            if (To.Count > 0)
            {
                foreach (var to in To)
                {
                    msg.To.Add(to);
                }
            }
            if (CC.Count > 0)
            {
                foreach (var cc in CC)
                {
                    msg.CC.Add(cc);
                }
            }
            if (BCC.Count > 0)
            {
                foreach (var bcc in BCC)
                {
                    msg.Bcc.Add(bcc);
                }
            }
            msg.From = new MailAddress(MailAddress, MailDisplayName, System.Text.Encoding.UTF8);
            /* 上面3个参数分别是发件人地址(可以随便写),发件人姓名,编码*/
            msg.Subject         = Subject;                   //邮件标题
            msg.SubjectEncoding = System.Text.Encoding.UTF8; //邮件标题编码
            msg.Body            = Body;                      //邮件内容
            msg.BodyEncoding    = System.Text.Encoding.UTF8; //邮件内容编码
            msg.IsBodyHtml      = true;                      //是否是HTML邮件
            msg.Priority        = Priority;                  //邮件优先级

            SmtpClient client = new SmtpClient();

            client.Credentials = new System.Net.NetworkCredential(MailAddress, MailPassword);
            //在zj.com注册的邮箱和密码
            client.Host = MailHost;
            client.Port = MailPort;
            object userState = msg;

            try
            {
                client.Send(msg);
                //简单一点儿可以client.Send(msg);
            }
            catch (Exception ex)
            {
                Log.Instance.Error(ex);
            }
        }
Esempio n. 29
0
        public static void Send(string smtpHost, int smtpPort, string from, string to, string subject, string body, bool isBodyHtml, Encoding bodyEncoding, Encoding subjectEncoding, MailPriority priority)
        {
            using (var message = new MailMessage())
            {
                if (!string.IsNullOrEmpty(from))
                {
                    message.From = new MailAddress(from);
                }

                message.To.Add(to);

                if (!string.IsNullOrEmpty(subject))
                {
                    message.Subject = subject;
                }

                if (!string.IsNullOrEmpty(body))
                {
                    message.Body = body;
                }

                if (bodyEncoding != null)
                {
                    message.BodyEncoding = bodyEncoding;
                }
                if (subjectEncoding != null)
                {
                    message.SubjectEncoding = subjectEncoding;
                }

                message.IsBodyHtml = isBodyHtml;
                message.Priority   = priority;

                Send(smtpHost, smtpPort, message);
            }
        }
Esempio n. 30
0
 public bool SendMail(string to, string subj, string message,
                      MailPriority priority, string attachmentFileName, Stream attachmentStream, out string errMessage)
 {
     return(SendMail(new string[] { to }, subj, message, priority, attachmentFileName, attachmentStream,
                     out errMessage));
 }
Esempio n. 31
0
        private static string SendMailInternal(MailMessage mailMessage, string subject, string body, MailPriority priority,
                                               MailFormat bodyFormat, Encoding bodyEncoding, IEnumerable <Attachment> attachments,
                                               string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL)
        {
            string retValue;

            mailMessage.Priority   = (System.Net.Mail.MailPriority)priority;
            mailMessage.IsBodyHtml = (bodyFormat == MailFormat.Html);

            //attachments
            foreach (var attachment in attachments)
            {
                mailMessage.Attachments.Add(attachment);
            }

            //message
            mailMessage.SubjectEncoding = bodyEncoding;
            mailMessage.Subject         = HtmlUtils.StripWhiteSpace(subject, true);
            mailMessage.BodyEncoding    = bodyEncoding;

            //added support for multipart html messages
            //add text part as alternate view
            var PlainView = AlternateView.CreateAlternateViewFromString(ConvertToText(body), null, "text/plain");

            mailMessage.AlternateViews.Add(PlainView);
            if (mailMessage.IsBodyHtml)
            {
                var HTMLView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
                mailMessage.AlternateViews.Add(HTMLView);
            }

            if (!String.IsNullOrEmpty(smtpServer))
            {
                try
                {
                    var smtpClient = new SmtpClient();

                    var smtpHostParts = smtpServer.Split(':');
                    smtpClient.Host = smtpHostParts[0];
                    if (smtpHostParts.Length > 1)
                    {
                        smtpClient.Port = Convert.ToInt32(smtpHostParts[1]);
                    }

                    switch (smtpAuthentication)
                    {
                    case "":
                    case "0":     //anonymous
                        break;

                    case "1":     //basic
                        if (!String.IsNullOrEmpty(smtpUsername) && !String.IsNullOrEmpty(smtpPassword))
                        {
                            smtpClient.UseDefaultCredentials = false;
                            smtpClient.Credentials           = new NetworkCredential(smtpUsername, smtpPassword);
                        }
                        break;

                    case "2":     //NTLM
                        smtpClient.UseDefaultCredentials = true;
                        break;
                    }
                    smtpClient.EnableSsl = smtpEnableSSL;
                    smtpClient.Send(mailMessage);
                    retValue = "";
                }
                catch (SmtpFailedRecipientException exc)
                {
                    retValue = string.Format(Localize.GetString("FailedRecipient"), exc.FailedRecipient);
                    Exceptions.Exceptions.LogException(exc);
                }
                catch (SmtpException exc)
                {
                    retValue = Localize.GetString("SMTPConfigurationProblem");
                    Exceptions.Exceptions.LogException(exc);
                }
                catch (Exception exc)
                {
                    //mail configuration problem
                    if (exc.InnerException != null)
                    {
                        retValue = string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message);
                        Exceptions.Exceptions.LogException(exc.InnerException);
                    }
                    else
                    {
                        retValue = exc.Message;
                        Exceptions.Exceptions.LogException(exc);
                    }
                }
                finally
                {
                    mailMessage.Dispose();
                }
            }
            else
            {
                retValue = Localize.GetString("SMTPConfigurationProblem");
            }

            return(retValue);
        }
Esempio n. 32
0
 public Boolean Send(string mailTo, string mailSubject, string mailBody, string[] attachments, MailPriority priority, bool isBodyHtml, System.Text.Encoding bodyEncoding)
 {
     string[] mailTos = new string[] { mailTo };
     return(Send(mailTos, null, null, mailSubject, mailBody, attachments, priority, isBodyHtml, bodyEncoding));
 }
Esempio n. 33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Email" /> class.
 /// </summary>
 /// <param name="smtpServerName">Name of the SMTP server.</param>
 /// <param name="fromAddress">From address.</param>
 /// <param name="toAddress">To address.</param>
 /// <param name="toAddressCC">To address CC.</param>
 /// <param name="subject">The subject.</param>
 /// <param name="body">The body.</param>
 /// <param name="attachments">The attachments.</param>
 /// <param name="priority">The priority.</param>
 public Email(string smtpServerName, string fromAddress, string toAddress,
              string toAddressCC, string subject, string body, string attachments, MailPriority priority)
     : this(smtpServerName, fromAddress, toAddress, toAddressCC, subject, body, attachments, priority, false)
 {
 }
Esempio n. 34
0
 public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body,
                               string attachment, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL)
 {
     return(SendMail(mailFrom,
                     mailTo,
                     cc,
                     bcc,
                     mailFrom,
                     priority,
                     subject,
                     bodyFormat,
                     bodyEncoding,
                     body,
                     attachment.Split('|'),
                     smtpServer,
                     smtpAuthentication,
                     smtpUsername,
                     smtpPassword,
                     smtpEnableSSL));
 }
Esempio n. 35
0
        public static int SendPasswordReminder(string username, string ip)
        {
            // place log record
            TaskManager.StartTask("USER", "SEND_REMINDER", username);
            TaskManager.WriteParameter("IP", ip);

            try
            {
                // try to get user from database
                UserInfo user = GetUserInternally(username);
                if (user == null)
                {
                    TaskManager.WriteWarning("Account not found");
                    // Fix for item #273 (NGS-9)
                    //return BusinessErrorCodes.ERROR_USER_NOT_FOUND;
                    return(0);
                }

                UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.PASSWORD_REMINDER_LETTER);
                string       from     = settings["From"];
                string       cc       = settings["CC"];
                string       subject  = settings["Subject"];
                string       body     = user.HtmlMail ? settings["HtmlBody"] : settings["TextBody"];
                bool         isHtml   = user.HtmlMail;

                MailPriority priority = MailPriority.Normal;
                if (!String.IsNullOrEmpty(settings["Priority"]))
                {
                    priority = (MailPriority)Enum.Parse(typeof(MailPriority), settings["Priority"], true);
                }

                if (body == null || body == "")
                {
                    return(BusinessErrorCodes.ERROR_SETTINGS_PASSWORD_LETTER_EMPTY_BODY);
                }

                // set template context items
                Hashtable items = new Hashtable();
                items["user"]  = user;
                items["Email"] = true;

                // get reseller details
                UserInfo reseller = UserController.GetUser(user.OwnerId);
                if (reseller != null)
                {
                    reseller.Password = "";
                    items["reseller"] = reseller;
                }

                subject = PackageController.EvaluateTemplate(subject, items);
                body    = PackageController.EvaluateTemplate(body, items);

                // send message
                MailHelper.SendMessage(from, user.Email, cc, subject, body, priority, isHtml);

                return(0);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 36
0
        public void SendMail(string smtpserver, int?port, string userName, string password, string from_mail, string from_alias, string to_mail, string to_alias, string title, string content, bool ishtml, bool enableSsl, Encoding encoding, MailPriority priority)
        {
            SmtpClient smtpClient = new SmtpClient();

            smtpClient.Host = smtpserver;
            if (port.HasValue)
            {
                smtpClient.Port = port.Value;
            }
            smtpClient.EnableSsl             = enableSsl;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials           = new NetworkCredential(userName, password);
            smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
            MailAddress from = new MailAddress(from_mail);

            if (!string.IsNullOrEmpty(from_alias))
            {
                from = new MailAddress(from_mail, from_alias);
            }
            MailAddress to = new MailAddress(to_mail);

            if (!string.IsNullOrEmpty(to_alias))
            {
                to = new MailAddress(to_mail, to_alias);
            }
            MailMessage mailMessage = new MailMessage(from, to);

            mailMessage.Subject      = title;
            mailMessage.Body         = content;
            mailMessage.BodyEncoding = encoding;
            mailMessage.IsBodyHtml   = ishtml;
            mailMessage.Priority     = priority;
            mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
            try
            {
                smtpClient.Send(mailMessage);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 37
0
        /// <summary>
        /// Initializes the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        public override void Initialize(CategoryPropertyItem item)
        {
            if (item == null)
            {
                ThrowHelper.ThrowArgumentNullException("item");
            }

            base.Initialize(item);

            SmtpAppender.SmtpAuthentication authMode = SmtpAppender.SmtpAuthentication.None;
            if (ConfigurationAccessHelper.ParseEnumValue <SmtpAppender.SmtpAuthentication>(item.PropertyItems, CONFIG_AUTHENTICATION, ref authMode))
            {
                this.Authentication = authMode;
            }

            string bcc = string.Empty;

            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_BCC, ref bcc))
            {
                this.Bcc = bcc;
            }

            #region Body Encoding

            string bodyEncoding = "Default";
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_BODYENCODING, ref bodyEncoding))
            {
                switch (bodyEncoding)
                {
                case "Default":
                {
                    this.BodyEncoding = Encoding.Default;
                }
                break;

                case "ASCII":
                {
                    this.BodyEncoding = Encoding.ASCII;
                }
                break;

                case "BigEndianUnicode":
                {
                    this.BodyEncoding = Encoding.BigEndianUnicode;
                }
                break;

                case "Unicode":
                {
                    this.BodyEncoding = Encoding.Unicode;
                }
                break;

                case "UTF32":
                {
                    this.BodyEncoding = Encoding.UTF32;
                }
                break;

                case "UTF7":
                {
                    this.BodyEncoding = Encoding.UTF7;
                }
                break;

                case "UTF8":
                {
                    this.BodyEncoding = Encoding.UTF8;
                }
                break;

                case "":
                case null:
                    break;

                default:
                {
                    this.BodyEncoding = Encoding.GetEncoding(bodyEncoding);
                }
                break;
                }
            }

            #endregion

            string cc = string.Empty;
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_CC, ref cc))
            {
                this.Cc = cc;
            }

            bool enableSsl = false;
            if (ConfigurationAccessHelper.ParseBooleanValue(item.PropertyItems, CONFIG_ENABLESSL, ref enableSsl))
            {
                this.EnableSsl = enableSsl;
            }

            string from = string.Empty;
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_FROM, ref from))
            {
                this.From = from;
            }

            string password = string.Empty;
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_PASSWORD, ref password))
            {
                this.Password = password;
            }

            int port = 25;
            if (ConfigurationAccessHelper.ParseIntValue(item.PropertyItems, CONFIG_PORT, 1, 65535, ref port))
            {
                this.Port = port;
            }

            MailPriority prio = MailPriority.Normal;
            if (ConfigurationAccessHelper.ParseEnumValue <MailPriority>(item.PropertyItems, CONFIG_MAILPRIORITY, ref prio))
            {
                this.Priority = prio;
            }

            string replyTo = string.Empty;
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_REPLYTO, ref replyTo))
            {
                this.ReplyTo = replyTo;
            }

            string pattern = string.Empty;
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_LAYOUT_PATTERN, ref pattern))
            {
                this.ConversionPattern = pattern;
            }
            else
            {
                this.ConversionPattern = DEFAULT_LAYOUT_PATTERN;
            }

            string smtpHost = string.Empty;
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_SMTP_HOST, ref smtpHost))
            {
                this.SmtpHost = smtpHost;
            }

            string subject = string.Empty;
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_SUBJECT, ref subject))
            {
                this.Subject = subject;
            }

            #region Subject Encoding

            string subjectEncoding = "Default";
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_SUBJECTENCODING, ref subjectEncoding))
            {
                switch (bodyEncoding)
                {
                case "Default":
                {
                    this.SubjectEncoding = Encoding.Default;
                }
                break;

                case "ASCII":
                {
                    this.SubjectEncoding = Encoding.ASCII;
                }
                break;

                case "BigEndianUnicode":
                {
                    this.SubjectEncoding = Encoding.BigEndianUnicode;
                }
                break;

                case "Unicode":
                {
                    this.SubjectEncoding = Encoding.Unicode;
                }
                break;

                case "UTF32":
                {
                    this.SubjectEncoding = Encoding.UTF32;
                }
                break;

                case "UTF7":
                {
                    this.SubjectEncoding = Encoding.UTF7;
                }
                break;

                case "UTF8":
                {
                    this.SubjectEncoding = Encoding.UTF8;
                }
                break;

                case "":
                case null:
                    break;

                default:
                {
                    this.SubjectEncoding = Encoding.GetEncoding(bodyEncoding);
                }
                break;
                }
            }

            #endregion

            string to = string.Empty;
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_TO, ref to))
            {
                this.To = to;
            }

            string username = string.Empty;
            if (ConfigurationAccessHelper.ParseStringValue(item.PropertyItems, CONFIG_USERNAME, ref username))
            {
                this.Username = username;
            }

            LOGGER.Info(string.Format("{0}, Authentication: {1}, Bcc: {2}, BodyEncoding: {3}, Cc: {4}, EnableSSL: {5}, From: {6}, Password: {7}, Port: {8}, Priority: {9}, ReplyTo: {10}, SmtpHost: {11}, SubjectEncoding: {12}, To: {13}, Username: {14}",
                                      this.GetType().Name, this.Authentication.ToString(), this.Bcc, this.BodyEncoding.EncodingName, this.Cc,
                                      this.EnableSsl.ToString(), this.From, string.IsNullOrEmpty(this.Password) ? "not set" : "exist", this.Port.ToString(), this.Priority.ToString(), this.ReplyTo, this.SmtpHost, this.SubjectEncoding.EncodingName, this.To, this.Username));

            this.IsInitialized = true;
        }
Esempio n. 38
0
        public void SendMail(string smtpserver, int?port, string account, string pass, string from_alias, string title, string content, bool ishtml, Encoding encoding, MailPriority priority, Dictionary <string, string> to_list)
        {
            if (to_list.Count <= 0)
            {
                throw new Exception("邮件接收人地址不能为空");
            }
            if (to_list.Count >= 20)
            {
                throw new Exception("每次只能发送给少于20个接收人!");
            }
            SmtpClient smtpClient = new SmtpClient();

            smtpClient.Host = smtpserver;
            if (port.HasValue)
            {
                smtpClient.Port = port.Value;
            }
            smtpClient.EnableSsl             = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials           = new NetworkCredential(account, pass);
            smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
            MailAddress from = new MailAddress(account);

            if (!string.IsNullOrEmpty(from_alias))
            {
                from = new MailAddress(account, from_alias);
            }
            MailMessage mailMessage = new MailMessage();

            mailMessage.From = from;
            foreach (KeyValuePair <string, string> item in to_list)
            {
                if (string.IsNullOrEmpty(item.Value))
                {
                    mailMessage.To.Add(new MailAddress(item.Key));
                }
                else
                {
                    mailMessage.To.Add(new MailAddress(item.Key, item.Value));
                }
            }
            mailMessage.Subject      = title;
            mailMessage.Body         = content;
            mailMessage.BodyEncoding = encoding;
            mailMessage.IsBodyHtml   = ishtml;
            mailMessage.Priority     = priority;
            try
            {
                smtpClient.Send(mailMessage);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 39
0
 /// <summary>
 /// Send a message with a specified priority and attachment(s).
 /// </summary>
 /// <param name="priority">The priority of the message</param>
 /// <param name="attachment">Attachment location or list attachments separated by a ';'.</param>
 /// <returns></returns>
 public bool SendMessage(MailPriority priority, string attachment)
 {
     Attachments  = attachment;
     MailPriority = priority;
     return(SendMessage());
 }
Esempio n. 40
0
        public virtual void Load(Stream reader, bool headersOnly = false, int maxLength = 0, char?termChar = null)
        {
            _HeadersOnly = headersOnly;
            Headers      = null;
            Body         = null;


            var    headers = new StringBuilder();
            string line;

            while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding, termChar)) != null)
            {
                if (line.Trim().Length == 0)
                {
                    if (headers.Length == 0)
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                headers.AppendLine(line);
            }
            RawHeaders = headers.ToString();

            if (!headersOnly)
            {
                string boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary))
                {
                    var atts = new List <Attachment>();
                    var body = ParseMime(reader, boundary, ref maxLength, atts, Encoding, termChar);
                    if (!string.IsNullOrEmpty(body))
                    {
                        SetBody(body);
                    }

                    foreach (var att in atts)
                    {
                        (att.IsAttachment ? Attachments : AlternateViews).Add(att);
                    }

                    if (maxLength > 0)
                    {
                        reader.ReadToEnd(maxLength, Encoding);
                    }
                }
                else
                {
                    //	sometimes when email doesn't have a body, we get here with maxLength == 0 and we shouldn't read any further
                    string body = String.Empty;
                    if (maxLength > 0)
                    {
                        body = reader.ReadToEnd(maxLength, Encoding);
                    }

                    SetBody(body);
                }
            }

            if ((string.IsNullOrEmpty(Body) || Body.All(char.IsWhiteSpace) || ContentType.StartsWith("multipart/")) && AlternateViews.Count > 0)
            {
                var att = AlternateViews.GetTextView() ?? AlternateViews.GetHtmlView();
                if (att != null)
                {
                    Body = att.Body;
                    ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
                    ContentType             = att.Headers["Content-Type"].RawValue;
                }
            }

            Date      = Headers.GetDate();
            To        = Headers.GetMailAddresses("To").ToList();
            Cc        = Headers.GetMailAddresses("Cc").ToList();
            Bcc       = Headers.GetMailAddresses("Bcc").ToList();
            Sender    = Headers.GetMailAddresses("Sender").FirstOrDefault();
            ReplyTo   = Headers.GetMailAddresses("Reply-To").ToList();
            From      = Headers.GetMailAddresses("From").FirstOrDefault();
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum <MailPriority>("Importance");
            Subject    = Headers["Subject"].RawValue;
        }
        private string _Subject; //主题

        #endregion Fields

        #region Constructors

        public MailMessage()
        {
            _Recipients = new ArrayList();//收件人列表
            _Attachments = new MailAttachments();//附件
            _BodyFormat = MailFormat.HTML;//缺省的邮件格式为HTML
            _Priority = MailPriority.Normal;
            _Charset = "GB2312";
        }
Esempio n. 42
0
        /// <summary>
        /// Sends an email based on params.
        /// </summary>
        /// <param name="mailFrom">Email sender</param>
        /// <param name="mailTo">Recipients, can be more then one separated by semi-colons</param>
        /// <param name="cc">CC-recipients, can be more then one separated by semi-colons</param>
        /// <param name="bcc">BCC-recipients, can be more then one separated by semi-colons</param>
        /// <param name="replyTo">Reply-to email to be displayed for recipients</param>
        /// <param name="priority"><see cref="DotNetNuke.Services.Mail.MailPriority"/></param>
        /// <param name="subject">Subject of email</param>
        /// <param name="bodyFormat"><see cref="DotNetNuke.Services.Mail.MailFormat"/></param>
        /// <param name="bodyEncoding">Email Encoding from System.Text.Encoding</param>
        /// <param name="body">Body of email</param>
        /// <param name="attachments">List of filenames to attach to email</param>
        /// <param name="smtpServer">IP or ServerName of the SMTP server. When empty or null, then it takes from the HostSettings</param>
        /// <param name="smtpAuthentication">SMTP authentication method. Can be "0" - anonymous, "1" - basic, "2" - NTLM. When empty or null, then it takes from the HostSettings.</param>
        /// <param name="smtpUsername">SMTP authentication UserName. When empty or null, then it takes from the HostSettings.</param>
        /// <param name="smtpPassword">SMTP authentication Password. When empty or null, then it takes from the HostSettings.</param>
        /// <param name="smtpEnableSSL">Enable or disable SSL.</param>
        /// <returns>Returns an empty string on success mail sending. Otherwise returns an error description.</returns>
        /// <example>SendMail(	"*****@*****.**",
        ///						"*****@*****.**",
        ///						"[email protected];[email protected]",
        ///						"*****@*****.**",
        ///						"*****@*****.**",
        ///						MailPriority.Low,
        ///						"This is test email",
        ///						MailFormat.Text,
        ///						Encoding.UTF8,
        ///						"Test body. Test body. Test body.",
        ///						new string[] {"d:\documents\doc1.doc","d:\documents\doc2.doc"},
        ///						"mail.email.com",
        ///						"1",
        ///						"*****@*****.**",
        ///						"AdminPassword",
        ///						false);
        ///	</example>
        public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding,
                                      string body, string[] attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL)
        {
            var attachmentList = (from attachment in attachments
                                  where !String.IsNullOrEmpty(attachment)
                                  select new Attachment(attachment))
                                 .ToList();

            return(SendMail(mailFrom,
                            mailTo,
                            cc,
                            bcc,
                            replyTo,
                            priority,
                            subject,
                            bodyFormat,
                            bodyEncoding,
                            body,
                            attachmentList,
                            smtpServer,
                            smtpAuthentication,
                            smtpUsername,
                            smtpPassword,
                            smtpEnableSSL));
        }
Esempio n. 43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Email" /> class.
 /// </summary>
 /// <param name="smtpServerName">Name of the SMTP server.</param>
 /// <param name="fromAddress">From address.</param>
 /// <param name="toAddress">To address.</param>
 /// <param name="toAddressCC">To address CC.</param>
 /// <param name="subject">The subject.</param>
 /// <param name="body">The body.</param>
 /// <param name="priority">The priority.</param>
 /// <param name="isBodyHtml">if set to <c>true</c> [is body HTML].</param>
 public Email(string smtpServerName, string fromAddress, string toAddress,
              string toAddressCC, string subject, string body, MailPriority priority, bool isBodyHtml)
     : this(smtpServerName, fromAddress, toAddress, toAddressCC, subject, body, string.Empty, priority, isBodyHtml)
 {
 }
Esempio n. 44
0
        private static string SendMailInternal(MailMessage mailMessage, string subject, string body, MailPriority priority,
                                               MailFormat bodyFormat, Encoding bodyEncoding, IEnumerable <Attachment> attachments,
                                               string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL)
        {
            string retValue = string.Empty;

            mailMessage.Priority   = (System.Net.Mail.MailPriority)priority;
            mailMessage.IsBodyHtml = (bodyFormat == MailFormat.Html);

            //if the senderAddress is the email address of the Host then switch it smtpUsername if different
            //if display name of senderAddress is empty, then use Host.HostTitle for it
            if (mailMessage.Sender != null)
            {
                var senderAddress     = mailMessage.Sender.Address;
                var senderDisplayName = mailMessage.Sender.DisplayName;
                var needUpdateSender  = false;
                if (smtpUsername.Contains("@") && senderAddress == Host.HostEmail &&
                    !senderAddress.Equals(smtpUsername, StringComparison.InvariantCultureIgnoreCase))
                {
                    senderAddress    = smtpUsername;
                    needUpdateSender = true;
                }
                if (string.IsNullOrEmpty(senderDisplayName))
                {
                    senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle;
                    needUpdateSender  = true;
                }
                if (needUpdateSender)
                {
                    mailMessage.Sender = new MailAddress(senderAddress, senderDisplayName);
                }
            }
            else if (smtpUsername.Contains("@"))
            {
                mailMessage.Sender = new MailAddress(smtpUsername, Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle);
            }
            //attachments
            foreach (var attachment in attachments)
            {
                mailMessage.Attachments.Add(attachment);
            }

            //message
            mailMessage.SubjectEncoding = bodyEncoding;
            mailMessage.Subject         = HtmlUtils.StripWhiteSpace(subject, true);
            mailMessage.BodyEncoding    = bodyEncoding;

            //added support for multipart html messages
            //add text part as alternate view
            var PlainView = AlternateView.CreateAlternateViewFromString(ConvertToText(body), null, "text/plain");

            mailMessage.AlternateViews.Add(PlainView);
            if (mailMessage.IsBodyHtml)
            {
                var HTMLView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
                mailMessage.AlternateViews.Add(HTMLView);
            }

            if (!String.IsNullOrEmpty(smtpServer))
            {
                try
                {
                    //to workaround problem in 4.0 need to specify host name
                    using (var smtpClient = new SmtpClient())
                    {
                        var smtpHostParts = smtpServer.Split(':');
                        smtpClient.Host = smtpHostParts[0];
                        smtpClient.Port = smtpHostParts.Length > 1 ? Convert.ToInt32(smtpHostParts[1]) : 25;

                        smtpClient.ServicePoint.MaxIdleTime     = Host.SMTPMaxIdleTime;
                        smtpClient.ServicePoint.ConnectionLimit = Host.SMTPConnectionLimit;

                        switch (smtpAuthentication)
                        {
                        case "":
                        case "0":     //anonymous
                            break;

                        case "1":     //basic
                            if (!String.IsNullOrEmpty(smtpUsername) && !String.IsNullOrEmpty(smtpPassword))
                            {
                                smtpClient.UseDefaultCredentials = false;
                                smtpClient.Credentials           = new NetworkCredential(smtpUsername, smtpPassword);
                            }
                            break;

                        case "2":     //NTLM
                            smtpClient.UseDefaultCredentials = true;
                            break;
                        }
                        smtpClient.EnableSsl = smtpEnableSSL;
                        smtpClient.Send(mailMessage);
                        smtpClient.Dispose();
                    }
                }
                catch (Exception exc)
                {
                    var exc2 = exc as SmtpFailedRecipientException;
                    if (exc2 != null)
                    {
                        retValue = string.Format(Localize.GetString("FailedRecipient"), exc2.FailedRecipient) + " ";
                    }
                    else if (exc is SmtpException)
                    {
                        retValue = Localize.GetString("SMTPConfigurationProblem") + " ";
                    }

                    //mail configuration problem
                    if (exc.InnerException != null)
                    {
                        retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message);
                        Exceptions.Exceptions.LogException(exc.InnerException);
                    }
                    else
                    {
                        retValue += exc.Message;
                        Exceptions.Exceptions.LogException(exc);
                    }
                }
                finally
                {
                    mailMessage.Dispose();
                }
            }
            else
            {
                retValue = Localize.GetString("SMTPConfigurationProblem");
            }

            return(retValue);
        }
Esempio n. 45
0
 public Boolean Send(string[] mailTos, string mailSubject, string mailBody, MailPriority priority, bool isBodyHtml)
 {
     string[]             attachments  = null;
     System.Text.Encoding bodyEncoding = System.Text.Encoding.Default;
     return(Send(mailTos, null, null, mailSubject, mailBody, attachments, priority, isBodyHtml, bodyEncoding));
 }
Esempio n. 46
0
 public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding,
                               string body, List <Attachment> attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL)
 {
     return(SendMail(mailFrom,
                     string.Empty,
                     mailTo,
                     cc,
                     bcc,
                     replyTo,
                     priority,
                     subject,
                     bodyFormat,
                     bodyEncoding,
                     body,
                     attachments,
                     smtpServer,
                     smtpAuthentication,
                     smtpUsername,
                     smtpPassword,
                     smtpEnableSSL));
 }
Esempio n. 47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Email" /> class.
 /// </summary>
 /// <param name="smtpServerName">Name of the SMTP server.</param>
 /// <param name="fromAddress">From address.</param>
 /// <param name="toAddress">To address.</param>
 /// <param name="toAddressCC">To address CC.</param>
 /// <param name="subject">The subject.</param>
 /// <param name="body">The body.</param>
 /// <param name="attachments">The attachments.</param>
 /// <param name="priority">The priority.</param>
 /// <param name="isBodyHtml">if set to <c>true</c> [is body HTML].</param>
 public Email(string smtpServerName, string fromAddress, string toAddress,
              string toAddressCC, string subject, string body, string attachments, MailPriority priority, bool isBodyHtml)
     : this()
 {
     SMTPServerName = smtpServerName;
     FromAddress    = fromAddress;
     ToAddress      = toAddress;
     ToAddressCC    = toAddressCC;
     Subject        = subject;
     Body           = body;
     Attachments    = attachments;
     MailPriority   = priority;
     IsBodyHTML     = isBodyHtml;
 }
Esempio n. 48
0
        public static string SendMail(string mailFrom, string mailSender, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding,
                                      string body, List <Attachment> attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL)
        {
            //SMTP server configuration
            if (string.IsNullOrEmpty(smtpServer) && !string.IsNullOrEmpty(Host.SMTPServer))
            {
                smtpServer = Host.SMTPServer;
            }
            if (string.IsNullOrEmpty(smtpAuthentication) && !string.IsNullOrEmpty(Host.SMTPAuthentication))
            {
                smtpAuthentication = Host.SMTPAuthentication;
            }
            if (string.IsNullOrEmpty(smtpUsername) && !string.IsNullOrEmpty(Host.SMTPUsername))
            {
                smtpUsername = Host.SMTPUsername;
            }
            if (string.IsNullOrEmpty(smtpPassword) && !string.IsNullOrEmpty(Host.SMTPPassword))
            {
                smtpPassword = Host.SMTPPassword;
            }

            MailMessage mailMessage = null;

            if (PortalSettings.Current != null)
            {
                mailMessage = (UserController.GetUserByEmail(PortalSettings.Current.PortalId, mailFrom) != null)
                    ? new MailMessage
                {
                    From =
                        new MailAddress(mailFrom,
                                        UserController.GetUserByEmail(PortalSettings.Current.PortalId, mailFrom).DisplayName)
                }
                    : new MailMessage {
                    From = new MailAddress(mailFrom)
                };
            }
            else
            {
                mailMessage = new MailMessage {
                    From = new MailAddress(mailFrom)
                };
            }

            if (!string.IsNullOrEmpty(mailSender))
            {
                mailMessage.Sender = new MailAddress(mailSender);
            }

            if (!String.IsNullOrEmpty(mailTo))
            {
                //translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons
                mailTo = mailTo.Replace(";", ",");
                mailMessage.To.Add(mailTo);
            }
            if (!String.IsNullOrEmpty(cc))
            {
                //translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons
                cc = cc.Replace(";", ",");
                mailMessage.CC.Add(cc);
            }
            if (!String.IsNullOrEmpty(bcc))
            {
                //translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons
                bcc = bcc.Replace(";", ",");
                mailMessage.Bcc.Add(bcc);
            }
            if (replyTo != string.Empty)
            {
                mailMessage.ReplyToList.Add(new MailAddress(replyTo));
            }

            using (mailMessage)
            {
                return(SendMailInternal(mailMessage, subject, body, priority, bodyFormat, bodyEncoding,
                                        attachments, smtpServer, smtpAuthentication, smtpUsername, smtpPassword, smtpEnableSSL));
            }
        }
 /// <summary>
 /// Sets the message priority
 /// </summary>
 /// <param name="priority">The <see cref="MailPriority"/></param>
 /// <returns>The <see cref="MailMessageOptions"/> to allow method chaining</returns>
 public MailMessageOptions Priority(MailPriority priority)
 {
     this.actions.Add(m => m.Priority = priority);
     return(this);
 }
Esempio n. 50
0
 public static void Send(string fromAddress, string fromDisplay, string toAddress, string subject, string body,
                         bool isBodyHtml = true, MailPriority priority = MailPriority.Normal, MailSendType type = MailSendType.Smtp)
 {
     Send(fromAddress, fromDisplay, toAddress, subject, body, Encoding.UTF8, isBodyHtml, priority, type);
 }
Esempio n. 51
0
 public bool SendMail(string to, string subj, string message,
                      MailPriority priority, out string errMessage)
 {
     return(SendMail(to, subj, message, priority, null, null,
                     out errMessage));
 }
Esempio n. 52
0
        //============================================

        /// <summary>
        /// Función que permite enviar un correo electrónico
        /// </summary>
        /// <returns>true || false</returns>
        public bool sendSmtpEmail()
        {
            bool success = false;

            try
            {
                // Accedemos a la casilla de correo
                SmtpClient smtp_client = new SmtpClient();
                smtp_client.Port      = port;
                smtp_client.Host      = host;
                smtp_client.EnableSsl = (ssl.HasValue) ? ssl.Value : false;

                smtp_client.Timeout               = 20000;
                smtp_client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtp_client.UseDefaultCredentials = (useDefaultCredentials.HasValue) ? useDefaultCredentials.Value : true;
                smtp_client.Credentials           = new NetworkCredential(user, password);
                // Fin Acceso a la casilla

                // Definir Prioridad
                MailPriority mPriority = new MailPriority();

                if (priority < 0)
                {
                    priority = 0;
                }
                else if (priority > 2)
                {
                    priority = 0;
                }

                switch (priority)
                {
                case 0:
                    mPriority = MailPriority.Normal;
                    break;

                case 1:
                    mPriority = MailPriority.Low;
                    break;

                case 2:
                    mPriority = MailPriority.High;
                    break;
                }
                // Fin Prioridad

                MailMessage mail = new MailMessage();

                mail.From       = new MailAddress(user);
                mail.Subject    = subject;
                mail.Body       = body;
                mail.Priority   = mPriority;
                mail.IsBodyHtml = (isBodyHtml.HasValue) ? isBodyHtml.Value : true;

                // Agregar Destinatarios
                foreach (string email in recipients)
                {
                    //mail.To.Add(email);
                    mail.To.Add(new MailAddress(email));
                }

                // Agregamos Destinatarios Copiados en Email
                if (cc != null)
                {
                    foreach (string email in cc)
                    {
                        //mail.CC.Add(email);
                        mail.CC.Add(new MailAddress(email));
                    }
                }

                // Agregamos Copias ocultas
                if (bcc != null)
                {
                    foreach (string email in bcc)
                    {
                        //mail.Bcc.Add(email);
                        mail.Bcc.Add(new MailAddress(email));
                    }
                }

                // Agregamos los archivos Adjuntos
                if (attach_file != null)
                {
                    foreach (FileStream file in attach_file)
                    {
                        mail.Attachments.Add(new Attachment(file, file.Name));
                    }
                }

                smtp_client.Send(mail);

                success = true;
            }
            catch (Exception e)
            {
                success = false;
                throw new Exception("Error", e);
            }

            return(success);
        }
Esempio n. 53
0
        public static bool SendMail(string strMailFromAddress, string strMailDisplayName, string strMailFromPwd, string[] arrMailToAddress, string[] arrMailCcAddress, string[] arrMailBccAddress, string strSmtpServer, string strSubject, string strBody, string[] arrMailAttachment, bool boolIsBodyHtml, MailPriority mailPriority, Encoding mailEncoding, bool Async)
        {
            bool bool_Result = false;

            //发件人地址不能为空
            if (string.IsNullOrEmpty(strMailFromAddress))
            {
                return(bool_Result);
            }

            //发件人显示名称为空时,默认显示发件人地址
            if (string.IsNullOrEmpty(strMailDisplayName))
            {
                strMailDisplayName = strMailFromAddress;
            }

            //发件人密码不能为空
            if (string.IsNullOrEmpty(strMailFromPwd))
            {
                return(bool_Result);
            }

            //收件人地址不能为空
            if (arrMailToAddress == null)
            {
                return(bool_Result);
            }

            //Smtp服务器地址不能为空
            if (string.IsNullOrEmpty(strSmtpServer))
            {
                return(bool_Result);
            }

            //邮件标题不能为空
            if (string.IsNullOrEmpty(strSubject))
            {
                return(bool_Result);
            }

            //默认邮件编码为 UTF8
            if (mailEncoding == null)
            {
                mailEncoding = System.Text.Encoding.UTF8;
            }

            MailMessage mailMsg = new MailMessage();

            //发件人地址
            try
            {
                mailMsg.From = new MailAddress(strMailFromAddress, strMailDisplayName, mailEncoding);
            }
            catch (Exception)
            {
                return(bool_Result);
            }

            //收件人地址
            for (int i = 0; i < arrMailToAddress.Length; i++)
            {
                string temp = arrMailToAddress[i].Trim();
                mailMsg.To.Add(temp);
            }

            //抄送人地址
            if (arrMailCcAddress != null)
            {
                for (int i = 0; i < arrMailCcAddress.Length; i++)
                {
                    mailMsg.CC.Add(arrMailCcAddress[i]);
                }
            }

            //密送人地址
            if (arrMailBccAddress != null)
            {
                for (int i = 0; i < arrMailBccAddress.Length; i++)
                {
                    mailMsg.Bcc.Add(arrMailBccAddress[i]);
                }
            }

            //邮件标题
            mailMsg.Subject = strSubject;

            //邮件标题编码
            mailMsg.SubjectEncoding = mailEncoding;

            //邮件正文
            mailMsg.Body = strBody;

            //邮件正文编码
            mailMsg.BodyEncoding = mailEncoding;

            //含有附件
            if (arrMailAttachment != null)
            {
                for (int i = 0; i < arrMailAttachment.Length; i++)
                {
                    mailMsg.Attachments.Add(new Attachment(arrMailAttachment[i]));
                }
            }

            //邮件优先级
            mailMsg.Priority = mailPriority;

            //邮件正文是否是HTML格式
            mailMsg.IsBodyHtml = boolIsBodyHtml;



            SmtpClient smtpClient = new SmtpClient();

            //验证发件人用户名和密码
            smtpClient.Credentials = new System.Net.NetworkCredential(strMailFromAddress, strMailFromPwd);

            //Smtp服务器地址
            smtpClient.Host = strSmtpServer;

            object userState = mailMsg;

            try
            {
                if (Async)
                {
                    //绑定回调函数
                    smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

                    //异步发送邮件
                    smtpClient.SendAsync(mailMsg, userState);
                    bool_Result = true;
                }
                else
                {
                    //同步发送邮件
                    smtpClient.Send(mailMsg);
                    bool_Result = true;
                }
            }
            catch (Exception ex)
            {
                //处理异常
                Manager.SyncWriteLog("Program", ConfigReader.logPath, "邮件发送给" + arrMailToAddress[0] + "...失败! \r" + ex);
                return(false);
            }

            return(bool_Result);
        }
Esempio n. 54
0
 /// <summary>
 /// Save message with a specified priority and documentpath
 /// </summary>
 /// <param name="priority">the priority of the message</param>
 /// <returns></returns>
 public bool SaveMessage(MailPriority priority, string DocumentPath)
 {
     MailPriority = priority;
     return(SaveMessage(DocumentPath));
 }
Esempio n. 55
0
 public void Send(string from, string[] to, string[] cc, string[] bcc, string subject, string body, bool isHtml, MailPriority mailPri, string[] attachments)
 {
     System.Net.Mail.MailMessage msg = new MailMessage();
     msg.From = new MailAddress(from);
     foreach (var t in to)
     {
         msg.To.Add(t);
     }
     if (cc != null && cc.Length > 0)
     {
         foreach (var c in cc)
         {
             msg.CC.Add(c);
         }
     }
     if (bcc != null && bcc.Length > 0)
     {
         foreach (var b in bcc)
         {
             msg.Bcc.Add(b);
         }
     }
     msg.Subject    = subject;
     msg.Body       = body;
     msg.Priority   = mailPri;
     msg.IsBodyHtml = isHtml;
     if (attachments != null && attachments.Length > 0)
     {
         foreach (var att in attachments)
         {
             msg.Attachments.Add(new Attachment(att));
         }
     }
     Send(msg);
 }
Esempio n. 56
0
 /// <summary>
 /// Send a messages with a specified priority
 /// </summary>
 /// <param name="priority">the priority of the message</param>
 /// <returns></returns>
 public bool SendMessage(MailPriority priority)
 {
     MailPriority = priority;
     return(SendMessage());
 }
Esempio n. 57
0
 /// <summary>
 /// Default Constructor
 /// </summary>
 public EmailSender()
 {
     Attachment_ = null;
     Priority_ = MailPriority.Normal;
 }
Esempio n. 58
0
 public Mail Priority(MailPriority mailPriority)
 {
     GetMailPriority = mailPriority;
     return(this);
 }
 private string GetPriorityString(MailPriority mailPriority)
 {
     string priority = "Normal";
     if (mailPriority == MailPriority.Low)
     {
         priority = "Low";
     }
     else if (mailPriority == MailPriority.High)
     {
         priority = "High";
     }
     return priority;
 }
Esempio n. 60
0
    /// <summary>
    /// 发送邮件到指定收件人
    /// </summary>
    /// <remarks>
    ///  2013-11-18 18:55 Created By iceStone
    /// </remarks>
    /// <param name="tos">收件人地址列表</param>
    /// <param name="subject">主题</param>
    /// <param name="mailBody">正文内容(支持HTML)</param>
    /// <param name="ccs">抄送地址列表</param>
    /// <param name="bccs">密件抄送地址列表</param>
    /// <param name="priority">此邮件的优先级</param>
    /// <param name="attachments">附件列表</param>
    /// <returns>是否发送成功</returns>
    /// <exception cref="System.ArgumentNullException">attachments</exception>
    public static bool Send(string[] tos, string subject, string mailBody, string[] ccs, string[] bccs, MailPriority priority, params Attachment[] attachments)
    {
        if (attachments == null)
        {
            throw new ArgumentNullException("attachments");
        }
        if (tos.Length == 0)
        {
            return(false);
        }
        //创建Email实体
        var message = new MailMessage();

        message.From         = new MailAddress(SmtpUsername, SmtpDisplayName);
        message.Subject      = subject;
        message.Body         = mailBody;
        message.BodyEncoding = Encoding.UTF8;
        message.IsBodyHtml   = true;
        message.Priority     = priority;
        //插入附件
        foreach (var attachment in attachments)
        {
            message.Attachments.Add(attachment);
        }
        //插入收件人地址,抄送地址和密件抄送地址
        foreach (var to in tos.Where(c => !string.IsNullOrEmpty(c)))
        {
            message.To.Add(new MailAddress(to));
        }
        foreach (var cc in ccs.Where(c => !string.IsNullOrEmpty(c)))
        {
            message.CC.Add(new MailAddress(cc));
        }
        foreach (var bcc in bccs.Where(c => !string.IsNullOrEmpty(c)))
        {
            message.CC.Add(new MailAddress(bcc));
        }
        //创建SMTP客户端
        var client = new SmtpClient
        {
            Host           = SmtpServer,
            Credentials    = new System.Net.NetworkCredential(SmtpUsername, SmtpPassword),
            DeliveryMethod = SmtpDeliveryMethod.Network,
            EnableSsl      = SmtpEnableSsl,
            Port           = SmtpServerPort
        };

        //client.SendCompleted += Client_SendCompleted;
        //try
        //{
        //发送邮件
        client.Send(message);
        //client.SendAsync(message,DateTime.Now.ToString());

        //client.Dispose();
        //message.Dispose();
        return(true);
        //}
        //catch (Exception)
        //{
        //    throw;
        //}
    }