Example #1
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 + "'>";
            }
        }
        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 + "'>";
            }
        }
Example #3
0
        public void SendMail(string recipient, string body)
        {
            string     pGmailEmail     = "*****@*****.**";
            string     pGmailPassword  = "******";
            string     pTo             = recipient;       //[email protected]
            string     pSubject        = "Revature Housing Account";
            string     pBody           = body;            //Body
            MailFormat pFormat         = MailFormat.Text; //Text Message
            string     pAttachmentPath = string.Empty;    //No Attachments

            System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserver",
                "smtp.gmail.com");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
                "465");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/sendusing",
                "2");
            //sendusing: cdoSendUsingPort, value 2, for sending the message using
            //the network.

            //smtpauthenticate: Specifies the mechanism used when authenticating
            //to an SMTP
            //service over the network. Possible values are:
            //- cdoAnonymous, value 0. Do not authenticate.
            //- cdoBasic, value 1. Use basic clear-text authentication.
            //When using this option you have to provide the user name and password
            //through the sendusername and sendpassword fields.
            //- cdoNTLM, value 2. The current process security context is used to
            // authenticate with the service.
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //Use 0 for anonymous
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/sendusername",
                pGmailEmail);
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/sendpassword",
                pGmailPassword);
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
                "true");
            myMail.From       = pGmailEmail;
            myMail.To         = pTo;
            myMail.Subject    = pSubject;
            myMail.BodyFormat = pFormat;
            myMail.Body       = pBody;
            if (pAttachmentPath.Trim() != "")
            {
                MailAttachment MyAttachment =
                    new MailAttachment(pAttachmentPath);
                myMail.Attachments.Add(MyAttachment);
                myMail.Priority = System.Web.Mail.MailPriority.High;
            }

            SmtpMail.SmtpServer = "smtp.gmail.com:465";
            SmtpMail.Send(myMail);
        }
Example #4
0
        public static string SendMail(string mailFrom, string mailTo, string replyTo, string cc, string bcc, string subject, string body)
        {
            DotNetNuke.Services.Mail.MailPriority priority = DotNetNuke.Services.Mail.MailPriority.Normal;
            MailFormat        bodyFormat         = MailFormat.Html;
            Encoding          bodyEncoding       = Encoding.UTF8;
            List <Attachment> attachments        = new List <Attachment>();
            string            smtpServer         = Host.SMTPServer;
            string            smtpAuthentication = Host.SMTPAuthentication;
            string            smtpUsername       = Host.SMTPUsername;
            string            smtpPassword       = Host.SMTPPassword;
            bool smtpEnableSsl = Host.EnableSMTPSSL;

            string res = Mail.SendMail(mailFrom,
                                       mailTo,
                                       cc,
                                       bcc,
                                       replyTo,
                                       priority,
                                       subject,
                                       bodyFormat,
                                       bodyEncoding,
                                       body,
                                       attachments,
                                       smtpServer,
                                       smtpAuthentication,
                                       smtpUsername,
                                       smtpPassword,
                                       smtpEnableSsl);

            //Mail.SendEmail(replyTo, mailFrom, mailTo, subject, body);
            return(res);
        }
    public static bool SendEmail(string pGmailEmail, string pGmailPassword, string pTo, string pSubject, string pBody, MailFormat pFormat, string pAttachmentPath)
    {
        MailMessage myMail = new MailMessage();
        myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com");
        myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
        myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");
        myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
        myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", pGmailEmail);
        myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pGmailPassword);
        myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");

        myMail.Priority = MailPriority.High;
        myMail.From = pGmailEmail;
        myMail.To = pTo;
        myMail.Subject = pSubject;
        myMail.BodyFormat = pFormat;
        myMail.Body = pBody;

        if(pAttachmentPath.Trim() != "")
        {
            MailAttachment MyAttachment = new MailAttachment(pAttachmentPath);
            myMail.Attachments.Add(MyAttachment);
            myMail.Priority = MailPriority.High;
        }

        SmtpMail.SmtpServer = "smtp.gmail.com:465";
        System.Web.Mail.SmtpMail.Send(myMail);

        return true;
    }
Example #6
0
 private MailPriority _Priority;       //邮件优先级
 public MailMessage()
 {
     _Recipients  = new ArrayList();       //收件人列表
     _Attachments = new MailAttachments(); //附件
     _BodyFormat  = MailFormat.HTML;       //缺省的邮件格式为HTML
     _Priority    = MailPriority.Normal;
     _Charset     = "GB2312";
 }
 public MailMessage()
 {
     this._Recipients  = (IList) new ArrayList();
     this._Attachments = new MailAttachments();
     this._BodyFormat  = MailFormat.HTML;
     this._Priority    = MailPriority.Normal;
     this._Charset     = "GB2312";
 }
Example #8
0
        public string SendEmail(string from, string to, string cc, string bcc, string subject, string body, bool isHtml)
        {
            MailFormat mailFormat = isHtml ? MailFormat.Html : MailFormat.Text;

            body = InjectEmailCssIntoBody(body);

            return(DotNetNuke.Services.Mail.Mail.SendMail(from, to, cc, bcc, MailPriority.Normal, subject, mailFormat, Encoding.UTF8, body, "", "", "", "", ""));
        }
Example #9
0
    public static bool SendEmail(
        string pTo,
        string pSubject,
        string pBody,
        MailFormat pFormat)
    {
        string      pGmailEmail    = "*****@*****.**";
        string      pGmailPassword = "******";
        MailMessage myMail         = new MailMessage();

        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpserver",
            "smtp.gmail.com");
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
            "465");
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendusing",
            "2");
        //sendusing: cdoSendUsingPort, value 2, for sending the message using
        //the network.

        //smtpauthenticate: Specifies the mechanism used when authenticating
        //to an SMTP
        //service over the network. Possible values are:
        //- cdoAnonymous, value 0. Do not authenticate.
        //- cdoBasic, value 1. Use basic clear-text authentication.
        //When using this option you have to provide the user name and password
        //through the sendusername and sendpassword fields.
        //- cdoNTLM, value 2. The current process security context is used to
        // authenticate with the service.
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
        //Use 0 for anonymous
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendusername",
            pGmailEmail);
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendpassword",
            pGmailPassword);
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
            "true");
        myMail.Priority = MailPriority.High;


        myMail.From       = "*****@*****.**";
        myMail.To         = pTo;
        myMail.Subject    = pSubject;
        myMail.BodyFormat = pFormat;
        myMail.Body       = pBody;
        //pAttachmentPath =

        SmtpMail.SmtpServer = "smtp.gmail.com:465";
        System.Web.Mail.SmtpMail.Send(myMail);
        return(true);
    }
 public static bool sendMail(
     string ServerMail,
     int Port,
     string pFrom,
     string pTo,
     string pSubject,
     string pBody,
     MailFormat pFormat,
     string pAttachmentPath,
     string username,
     string password)
 {
     try
     {
         System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
         string str1     = pFrom;
         char[] chArray1 = new char[1] {
             ';'
         };
         foreach (string address in str1.Split(chArray1))
         {
             MailAddress mailAddress = new MailAddress(address);
             message.From = mailAddress;
         }
         string str2     = pTo;
         char[] chArray2 = new char[1] {
             ';'
         };
         foreach (string address in str2.Split(chArray2))
         {
             MailAddress mailAddress = new MailAddress(address);
             message.To.Add(mailAddress);
         }
         message.IsBodyHtml = pFormat == MailFormat.Html;
         message.Subject    = pSubject;
         message.Body       = pBody;
         if (!string.IsNullOrEmpty(pAttachmentPath))
         {
             Attachment attachment = new Attachment(pAttachmentPath);
             message.Attachments.Add(attachment);
         }
         SmtpClient smtpClient = new SmtpClient(ServerMail, Port);
         if (!string.IsNullOrEmpty(username))
         {
             smtpClient.UseDefaultCredentials = false;
             NetworkCredential networkCredential = new NetworkCredential(username, password);
             smtpClient.Credentials = (ICredentialsByHost)networkCredential;
         }
         smtpClient.Send(message);
         return(true);
     }
     catch
     {
         throw;
     }
 }
        protected void btnSend_Click(object sender, System.EventArgs e)
        {
            string [] adr        = txtAdr.Text.Split(',');
            string    strNotSent = "";

            lblInfo.ForeColor = Color.Red;
            lblInfo.Text      = "";
            Regex  rx      = new Regex(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
            string admAddr = Config.GetDbConfigValue(DBase, 1);

            if (!rx.IsMatch(admAddr))
            {
                lblInfo.Text = "Email Address of Administrator is'nt correct";
                return;
            }
            int notSent = 0;

            if (txtSubject.Text.Trim() == String.Empty)
            {
                lblInfo.Text = "Enter subject , please";
                return;
            }
            foreach (string sadr in adr)
            {
                string tadr = sadr.Trim();
                if (!rx.IsMatch(tadr))
                {
                    Common.Log.Write(this, "Email address is'nt correct :" + tadr);
                    notSent++;
                    strNotSent += (tadr + "<br>");
                }
                else
                {
                    MailFormat mf = ddSendAs.SelectedValue.ToLower() == "html"?MailFormat.Html : MailFormat.Text;
                    if (CommonUse.CSentMail.Send(DBase, tadr, admAddr, txtSubject.Text, txtmessage.Text, mf) != 0)
                    {
                        notSent++;
                    }
                    strNotSent += (tadr + "<br>");
                }
            }

            if (notSent == 0)
            {
                lblInfo.Text      = "Mail Sent OK";
                lblInfo.ForeColor = Color.Green;
            }
            else
            {
                lblInfo.Text   = String.Format("Mail has'nt been send to {0} addresses", notSent);
                lbNotSent.Text = strNotSent;
            }
        }
        public static void Send(string to, string subject, string body, MailFormat format)
        {
            MailMessage message = new MailMessage();

            message.From       = "\"GovTrack.us\" <*****@*****.**>";
            message.Subject    = subject;
            message.To         = to;
            message.Body       = body;
            message.BodyFormat = format;

            SmtpMail.Send(message);
        }
Example #13
0
 public Email()
 {
     this._conf = new SMTPSettings()
     {
         ServerName = "smtp.gmail.com",
         Password   = "******",
         UserName   = "******"
     };
     this._mail   = new Mail(_conf);
     this._format = new MailFormatTXT();
     this._msg    = new MailMessage("", _format);
 }
Example #14
0
        /// <Summary>Send a simple email.</Summary>
        public static string SendMail(string MailFrom, string MailTo, string Bcc, string Subject, string Body, string Attachment, string BodyType, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword)
        {
            // SMTP server configuration
            if (SMTPServer == "")
            {
                if (Convert.ToString(Globals.HostSettings["SMTPServer"]) != "")
                {
                    SMTPServer = Convert.ToString(Globals.HostSettings["SMTPServer"]);
                }
            }
            if (SMTPAuthentication == "")
            {
                if (Convert.ToString(Globals.HostSettings["SMTPAuthentication"]) != "")
                {
                    SMTPAuthentication = Convert.ToString(Globals.HostSettings["SMTPAuthentication"]);
                }
            }
            if (SMTPUsername == "")
            {
                if (Convert.ToString(Globals.HostSettings["SMTPUsername"]) != "")
                {
                    SMTPUsername = Convert.ToString(Globals.HostSettings["SMTPUsername"]);
                }
            }
            if (SMTPPassword == "")
            {
                if (Convert.ToString(Globals.HostSettings["SMTPPassword"]) != "")
                {
                    SMTPPassword = Convert.ToString(Globals.HostSettings["SMTPPassword"]);
                }
            }

            // here we check if we want to format the email as html or plain text.
            MailFormat objBodyFormat = MailFormat.Html;

            if (!String.IsNullOrEmpty(BodyType))
            {
                switch (BodyType.ToLower())
                {
                case "html":

                    objBodyFormat = MailFormat.Html;
                    break;

                case "text":

                    objBodyFormat = MailFormat.Text;
                    break;
                }
            }

            return(SendMail(MailFrom, MailTo, "", Bcc, MailPriority.Normal, Subject, objBodyFormat, Encoding.UTF8, Body, Attachment, SMTPServer, SMTPAuthentication, SMTPUsername, SMTPPassword));
        }
        /// <summary>
        /// Sends an email to specified address.
        /// </summary>
        /// <param name="From">Email address from</param>
        /// <param name="sendTo">Email address to</param>
        /// <param name="Subject">Email subject line</param>
        /// <param name="Body">Email body content</param>
        /// <param name="AttachmentFiles">Optional, list of attachment file names in form of an array list</param>
        /// <param name="CC">Email carbon copy to</param>
        /// <param name="BCC">Email blind carbon copy to</param>
        /// <param name="SMTPServer">SMTP Server to send mail thru (optional, if not specified local machine is used)</param>
        /// <param name="mf">Optional, mail format (text/html)</param>
        public static void SendEMail(string From, string sendTo, string Subject, string Body, ArrayList AttachmentFiles,
                                     string CC, string BCC, string SMTPServer, MailFormat mf)
        {
            MailMessage myMessage;

            try
            {
                myMessage = new MailMessage();
                myMessage.To.Add(sendTo);
                myMessage.From       = new MailAddress(From);
                myMessage.Subject    = Subject;
                myMessage.Body       = Body;
                myMessage.IsBodyHtml = (mf == MailFormat.Html ? true : false);

                if (CC.Length != 0)
                {
                    myMessage.CC.Add(CC);
                }

                if (BCC.Length != 0)
                {
                    myMessage.Bcc.Add(BCC);
                }

                if (AttachmentFiles != null)
                {
                    foreach (string x in AttachmentFiles)
                    {
                        if (File.Exists(x))
                        {
                            myMessage.Attachments.Add(new Attachment(x));
                        }
                    }
                }

                if (SMTPServer.Length != 0)
                {
                    SmtpClient smtp = new SmtpClient(SMTPServer);

                    smtp.Send(myMessage);
                }
                else
                {
                    throw new RainbowException("SMTPServer configuration error");
                }
            }

            catch (Exception myexp)
            {
                throw myexp;
            }
        }
 public bool SendMail(List<string> mailIds, string subject, string body, List<string> attachmentFilePaths)
 {
     try
     {
         var myMailMessage = new MailMessage();
         myMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com");
         myMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
         myMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");
         myMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
         //Use 0 for anonymous
         myMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", PGmailAccount);
         myMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", PGmailPassword);
         myMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
         myMailMessage.From = PGmailAccount;
         if (mailIds != null && mailIds.Count > 0)
         {
             string toMails = mailIds.Aggregate(string.Empty, (current, mailid) => current + (mailid + ";"));
             toMails = toMails.Substring(0, toMails.Length - 1);
             myMailMessage.To = toMails;
             myMailMessage.Subject = subject;
             var pFormat = new MailFormat();
             pFormat = MailFormat.Html;
             myMailMessage.BodyFormat = pFormat;
             myMailMessage.Body = body;
             //string pAttachmentPath = "//servername/filename"; //contains the path of the attachment (if any)
             //if (pAttachmentPath.Trim() != "")
             //{
             // MailAttachment MyEmailAttachment = new MailAttachment(pAttachmentPath);
             // myMailMessage.Attachments.Add(MyEmailAttachment);
             // myMailMessage.Priority = MailPriority.High;
             //}
             if (attachmentFilePaths != null && attachmentFilePaths.Count > 0)
             {
                 foreach (string attachmentFilePath in attachmentFilePaths)
                 {
                     var attachment = new MailAttachment(attachmentFilePath);
                     myMailMessage.Attachments.Add(attachment);
                 }
             }
             myMailMessage.Priority = MailPriority.High;
             SmtpMail.SmtpServer = "smtp.gmail.com:465";
             SmtpMail.Send(myMailMessage);
         }
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
Example #17
0
 public static void SendEMail(XmlNode emailConfigNode, string body, MailFormat format, string subject, bool highPriority, MailAttachment[] attachments)
 {
     try
     {
         string from       = emailConfigNode.SelectSingleNode(FROM_ADDRESS_TAG).InnerText;
         string to         = emailConfigNode.SelectSingleNode(TO_ADDRESS_TAG).InnerText;
         string smtpServer = emailConfigNode.SelectSingleNode(MAIL_SERVER_TAG).InnerText;
         SendEMail(from, to, smtpServer, body, format, subject, highPriority, attachments);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
 }
Example #18
0
        public void SendMail(string subject, string body, string from, string to, string application, MailPriority priority, MailFormat mailformat, string cc, string bcc, string attachments)
        {
            Application = application;
            FromAddress = from;
            ToAddress   = to;
            CClist      = cc;
            BCClist     = bcc;
            Filelist    = attachments;
            Subject     = subject;
            Priority    = priority;
            Mailformat  = mailformat;
            Body        = body;

            SendMail();
        }
Example #19
0
		public Mail(MailAddressCollection to, MailAddress from, string message, string subject, MailAddressCollection cc, MailAddressCollection bcc, MailAddress replyTo, MailAddress sender, bool senderHidden, string alternativeMessage, AttachmentCollection attachments, MailFormat format) {
			this.to = to;
			this.From = from;
			this.ReplyTo = replyTo;
			this.Sender = sender;
			this.Message = message;
			this.AlternativeMessage = alternativeMessage;
			this.Subject = subject;
			this.CC = cc;
			this.BCC = bcc;
			this.attachments = (attachments ?? new AttachmentCollection());
			this.headers = new NameValueCollection();
			this.Format = format;
			this.SenderHidden = senderHidden;
		}
Example #20
0
    private void LoadMailFormat()
    {
        if (!AddingNew)
        {
            ddlTypes.DataBind();
            MailFormat mailFormat = MailFormatService.GetMailFormat(MailFormatId);

            txtName.Text           = mailFormat.FormatName;
            lblHead.Text           = mailFormat.FormatName;
            CKEditorControl1.Text  = mailFormat.FormatText;
            chkActive.Checked      = mailFormat.Enable;
            txtSortOrder.Text      = mailFormat.SortOrder.ToString(CultureInfo.InvariantCulture);
            ddlTypes.SelectedValue = ((int)mailFormat.FormatType).ToString(CultureInfo.InvariantCulture);
            ShowMailFormatTypeDescription();

            Page.Title = string.Format("{0} - {1}", AdvantShop.Configuration.SettingsMain.ShopName, mailFormat.FormatName);
        }
    }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (txtName.Text.Trim().Length == 0 || txtSubject.Text.Trim().Length == 0)
            {
                MsgErr(Resource.Admin_MailFormat_NoName);
                return;
            }

            if (CKEditorControl1.Text.Trim().Length == 0)
            {
                MsgErr(Resource.Admin_MailFormat_NoText);
                return;
            }

            int result = 0;

            if (!Int32.TryParse(txtSortOrder.Text, out result))
            {
                MsgErr(Resource.Admin_MailFormat_SortNotNum);
                return;
            }

            MailFormat mailFormat = AddingNew ? new MailFormat() : MailFormatService.Get(MailFormatId);

            mailFormat.FormatName    = txtName.Text.Trim();
            mailFormat.FormatSubject = txtSubject.Text.Trim();
            mailFormat.FormatText    = CKEditorControl1.Text.Trim();
            mailFormat.Enable        = chkActive.Checked;
            mailFormat.SortOrder     = Int32.Parse(txtSortOrder.Text);
            mailFormat.FormatType    = (MailType)Int32.Parse(ddlTypes.SelectedValue);

            if (AddingNew)
            {
                MailFormatService.Add(mailFormat);
                Response.Redirect("MailFormat.aspx");
            }
            else
            {
                lblMessage.Text    = Resource.Admin_MailFormatDetail_Saved + "<br />";
                lblMessage.Visible = true;
                MailFormatService.Update(mailFormat);
                LoadMailFormat();
            }
        }
Example #22
0
 ///////////////////////////////////////////////////////////////////////
 public static string send_email( // 6 args
     string to,
     string from,
     string cc,
     string subject,
     string body,
     MailFormat body_format)
 {
     return send_email(
         to,
         from,
         cc,
         subject,
         body,
         body_format,
         MailPriority.Normal,
         null,
         false);
 }
Example #23
0
 ///////////////////////////////////////////////////////////////////////
 public static string send_email( // 6 args
     string to,
     string from,
     string cc,
     string subject,
     string body,
     MailFormat body_format)
 {
     return(send_email(
                to,
                from,
                cc,
                subject,
                body,
                body_format,
                MailPriority.Normal,
                null,
                false));
 }
        public static void QuickSend(
            string SMTPServerName,
            string ToEmail,
            string FromEmail,
            string Subject,
            string Body,
            MailFormat BodyFormat)
        {
            EnhancedMailMessage msg = new EnhancedMailMessage();

            msg.From       = FromEmail;
            msg.To         = ToEmail;
            msg.Subject    = Subject;
            msg.Body       = Body;
            msg.BodyFormat = BodyFormat;

            msg.SMTPServerName = SMTPServerName;
            msg.Send();
        }
Example #25
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// <summary>Send a simple email.</summary>
        /// </summary>
        /// <param name="mailFrom"></param>
        /// <param name="mailTo"></param>
        /// <param name="bcc"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="attachment"></param>
        /// <param name="bodyType"></param>
        /// <param name="smtpServer"></param>
        /// <param name="smtpAuthentication"></param>
        /// <param name="smtpUsername"></param>
        /// <param name="smtpPassword"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        /// -----------------------------------------------------------------------------
        public static string SendMail(string mailFrom, string mailTo, string bcc, string subject, string body, string attachment, string bodyType, string smtpServer, string smtpAuthentication,
                                      string smtpUsername, string smtpPassword)
        {
            MailFormat bodyFormat = MailFormat.Text;

            if (!String.IsNullOrEmpty(bodyType))
            {
                switch (bodyType.ToLower())
                {
                case "html":
                    bodyFormat = MailFormat.Html;
                    break;

                case "text":
                    bodyFormat = MailFormat.Text;
                    break;
                }
            }
            return(SendMail(mailFrom, mailTo, "", bcc, MailPriority.Normal, subject, bodyFormat, Encoding.UTF8, body, attachment, smtpServer, smtpAuthentication, smtpUsername, smtpPassword));
        }
Example #26
0
        public static string SendMail(string MailFrom, string MailTo, string Bcc, string Subject, string Body, string Attachment, string BodyType, string SMTPServer, string SMTPAuthentication, string SMTPUsername,
                                      string SMTPPassword)
        {
            MailFormat objBodyFormat = MailFormat.Text;

            if (!String.IsNullOrEmpty(BodyType))
            {
                switch (BodyType.ToLower())
                {
                case "html":
                    objBodyFormat = MailFormat.Html;
                    break;

                case "text":
                    objBodyFormat = MailFormat.Text;
                    break;
                }
            }
            return(SendMail(MailFrom, MailTo, "", Bcc, MailPriority.Normal, Subject, objBodyFormat, System.Text.Encoding.UTF8, Body, Attachment,
                            SMTPServer, SMTPAuthentication, SMTPUsername, SMTPPassword));
        }
Example #27
0
 private static bool SendMail(string to,string bcc,string cc,string from,MailFormat  format,string subject,string body,string server)
 {
     MailMessage msg = new MailMessage();
     msg.To = to;
     msg.Bcc=bcc;
     msg.Cc=cc;
     msg.From=from;
     msg.BodyFormat= format;
     msg.Subject=subject;
     msg.Body=body;
     SmtpMail.SmtpServer=server;
     try
     {
         SmtpMail.Send(msg);
     }
     catch(Exception e)
     {
     HttpContext.Current.Response.Write(e.Message);
     }
     return true;
 }
Example #28
0
        private void SendEmail(string _from, string _to, string _cc, string _bcc, string _subject, string _body)
        {
            MailFormat   _mailFormat   = MailFormat.Html;
            MailPriority _mailPriority = MailPriority.High;
            MailMessage  _mailMSG      = new MailMessage();

            _mailMSG.From       = _from;
            _mailMSG.To         = _to;
            _mailMSG.Cc         = _cc;
            _mailMSG.Bcc        = _bcc;
            _mailMSG.Subject    = _subject;
            _mailMSG.Body       = _body;
            _mailMSG.Priority   = _mailPriority;
            _mailMSG.BodyFormat = _mailFormat;

            string _SMTPServer = ConfigurationManager.AppSettings["MailServer"].Trim();

            SmtpMail.SmtpServer = _SMTPServer;

            SmtpMail.Send(_mailMSG);
        }
Example #29
0
 public static bool SendEmail(
     string pGmailEmail,
     string pGmailPassword,
     string pTo,
     string pSubject,
     string pBody,
     MailFormat pFormat,
     string pAttachmentPath)
 {
     try
     {
         MailMessage message = new MailMessage();
         message.Fields.Add((object)"http://schemas.microsoft.com/cdo/configuration/smtpserver", (object)"smtp.gmail.com");
         message.Fields.Add((object)"http://schemas.microsoft.com/cdo/configuration/smtpserverport", (object)"465");
         message.Fields.Add((object)"http://schemas.microsoft.com/cdo/configuration/sendusing", (object)"2");
         message.Fields.Add((object)"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", (object)"1");
         message.Fields.Add((object)"http://schemas.microsoft.com/cdo/configuration/sendusername", (object)pGmailEmail);
         message.Fields.Add((object)"http://schemas.microsoft.com/cdo/configuration/sendpassword", (object)pGmailPassword);
         message.Fields.Add((object)"http://schemas.microsoft.com/cdo/configuration/smtpusessl", (object)"true");
         message.From       = pGmailEmail;
         message.To         = pTo;
         message.Subject    = pSubject;
         message.BodyFormat = pFormat;
         message.Body       = pBody;
         if (pAttachmentPath.Trim() != "")
         {
             MailAttachment mailAttachment = new MailAttachment(pAttachmentPath);
             message.Attachments.Add((object)mailAttachment);
             message.Priority = MailPriority.High;
         }
         SmtpMail.SmtpServer = "smtp.gmail.com:465";
         SmtpMail.Send(message);
         return(true);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
        private static bool SendMail(string to, string bcc, string cc, string from, MailFormat format, string subject, string body, string server)
        {
            MailMessage msg = new MailMessage();

            msg.To              = to;
            msg.Bcc             = bcc;
            msg.Cc              = cc;
            msg.From            = from;
            msg.BodyFormat      = format;
            msg.Subject         = subject;
            msg.Body            = body;
            SmtpMail.SmtpServer = server;
            try
            {
                SmtpMail.Send(msg);
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write(e.Message);
            }
            return(true);
        }
Example #31
0
 public static string SendMail(string MailFrom, string MailTo, string Cc, string Bcc, string ReplyTo, MailPriority Priority, string Subject, MailFormat BodyFormat, System.Text.Encoding BodyEncoding, string Body,
 string[] Attachment, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword, bool SMTPEnableSSL)
 {
     List<Attachment> attachments = new List<Attachment>();
     foreach (string myAtt in Attachment)
     {
         if (!String.IsNullOrEmpty(myAtt))
             attachments.Add(new Attachment(myAtt));
     }
     return SendMail(MailFrom, MailTo, Cc, Bcc, ReplyTo, Priority, Subject, BodyFormat, BodyEncoding, Body,
     attachments, SMTPServer, SMTPAuthentication, SMTPUsername, SMTPPassword, SMTPEnableSSL);
 }
Example #32
0
        /// <summary>
        /// Send an e-mail message with optional attachments.
        /// </summary>
        /// <example>
        /// <code>
        /// using Argentini.Halide;
        /// ...
        /// ArrayList AttachMe = new ArrayList();
        /// AttachMe.Add("/ftp/file1.pdf");
        /// AttachMe.Add("/ftp/file2.pdf");
        /// 
        /// string result = H3Email.Send(
        ///		"*****@*****.**",
        ///		"John Sender",
        ///		"[email protected],[email protected]",
        ///		"[email protected],[email protected]",
        ///		"[email protected],[email protected]",
        ///		"Message subject here",
        ///		"This is the message body.",
        ///		H3Email.MailFormat.PlainText,
        ///		AttachMe);
        /// </code>
        /// </example>
        /// <param name="senderAddress">From address (i.e. [email protected]).</param>
        /// <param name="senderName">From name (i.e. Joe).</param>
        /// <param name="recipient">To address(es), separated by commas.</param>
        /// <param name="ccList">Comma-separated list of e-mail addresses for carbon copies.</param>
        /// <param name="bccList">Comma-separated list of e-mail addresses for blind carbon copies.</param>
        /// <param name="subject">Message subject.</param>
        /// <param name="body">Message body.</param>
        /// <param name="bodyFormat">MailFormat value.</param>
        /// <param name="attachments">ArrayList object with virtual paths to files OR memory streams.</param>
        /// <param name="attachmentNames">ArrayList object with filenames for memory stream attachments.</param>
        /// <param name="useSsl">Should SMTP use SSL</param>
        /// <returns>"SUCCESS", or an error message.</returns>
        public static String Send(String senderAddress, String senderName, String recipient, String ccList, String bccList, String subject, String body, MailFormat bodyFormat, ArrayList attachments, ArrayList attachmentNames, Boolean useSsl)
        {
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

            if (String.IsNullOrEmpty(senderName))
            {
                mail.From = new MailAddress(senderAddress);
            }

            else
            {
                mail.From = new MailAddress(senderAddress, senderName);
            }

            mail.Subject = subject;
            mail.Body = body;

            foreach (String address in recipient.Split(',')) mail.To.Add(address);

            if (!String.IsNullOrEmpty(ccList))
            {
                foreach (String address in ccList.Split(',')) mail.CC.Add(address);
            }

            if (!String.IsNullOrEmpty(bccList))
            {
                foreach (String address in bccList.Split(',')) mail.Bcc.Add(address);
            }

            String result = "SUCCESS";

            AlternateView newBody = AlternateView.CreateAlternateViewFromString(
                            body,
                            Encoding.ASCII,
                            "text/plain");

            try
            {
                mail.IsBodyHtml = (bodyFormat == MailFormat.Html ? true : false);

                if (bodyFormat == MailFormat.PlainText7Bit)
                {
                    mail.Body = null;
                    newBody.TransferEncoding = TransferEncoding.SevenBit;
                    mail.AlternateViews.Add(newBody);
                }

                if (attachments != null)
                {
                    if (attachments.Count > 0)
                    {
                        for(int x = 0; x < attachments.Count; x++)
                        {
                            System.Net.Mail.Attachment data = null;

                            if (attachments[x].GetType() == typeof(string) || attachments[x].GetType() == typeof(String))
                            {
                                data = new System.Net.Mail.Attachment(HttpContext.Current.Server.MapPath((string)attachments[x]), MediaTypeNames.Application.Octet);
                                data.ContentId = attachments[x].ToString().Substring((attachments[x].ToString().LastIndexOf("/") == 0 ? 0 : attachments[x].ToString().LastIndexOf("/") + 1));
                            }

                            else if (attachments[x].GetType() == typeof(MemoryStream) && attachmentNames.Count == attachments.Count && attachmentNames[x] != null)
                            {
                                data = new System.Net.Mail.Attachment((MemoryStream)attachments[x], (string)attachmentNames[x]);
                            }

                            if (data != null)
                            {
                                mail.Attachments.Add(data);
                            }
                        }
                    }
                }

                SmtpClient smtp = new SmtpClient();

                smtp.EnableSsl = useSsl;

                smtp.Send( mail );

                if (newBody != null)
                {
                    newBody.Dispose();
                }

                mail.Dispose();
            }

            catch (Exception err)
            {
                result = err.ToString();
            }

            return result;
        }
Example #33
0
 /// <summary>
 /// Send an e-mail message.
 /// </summary>
 /// <example>
 /// <code>
 /// using Argentini.Halide;
 /// ...
 /// string result = H3Email.Send(
 ///		"*****@*****.**",
 ///		"[email protected],[email protected]",
 ///		"Message subject here",
 ///		"This is the message body.",
 ///		H3Email.MailFormat.PlainText);
 /// </code>
 /// </example>
 /// <param name="sender">From address (i.e. [email protected]).</param>
 /// <param name="recipient">To address(es), separated by commas.</param>
 /// <param name="subject">Message subject.</param>
 /// <param name="body">Message body.</param>
 /// <param name="bodyFormat">MailFormat value.</param>
 /// <returns>"SUCCESS", or an error message.</returns>
 public static String Send(string sender, string recipient, string subject, string body, MailFormat bodyFormat)
 {
     ArrayList attachments = new ArrayList();
     return Send(sender, "", recipient, subject, body, bodyFormat, attachments);
 }
Example #34
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, ICollection <MailAttachment> 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));
 }
Example #35
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));
 }
Example #36
0
		public Mail(string to, string from, string message, string subject, string cc, string bcc, string replyTo, string sender, bool senderHidden, string alternativeMessage, AttachmentCollection attachments, MailFormat format) : this(GetMailAddressCollection(to), GetMailAddress(from), message, subject, GetMailAddressCollection(cc), GetMailAddressCollection(bcc), GetMailAddress(replyTo), GetMailAddress(sender), senderHidden, alternativeMessage, attachments, format) { }
Example #37
0
        /// <summary>
        /// Send an e-mail message with optional attsachments.
        /// </summary>
        /// <example>
        /// <code>
        /// using Mezzocode.Halide3;
        /// ...
        /// ArrayList AttachMe = new ArrayList();
        /// AttachMe.Add("/ftp/file1.pdf");
        /// AttachMe.Add("/ftp/file2.pdf");
        /// 
        /// string result = h3Email.Send(
        ///		"*****@*****.**",
        ///		"John Sender",
        ///		"[email protected],[email protected]",
        ///		"[email protected],[email protected]",
        ///		"[email protected],[email protected]",
        ///		"Message subject here",
        ///		"This is the message body.",
        ///		h3Email.MailFormat.PlainText,
        ///		AttachMe);
        /// </code>
        /// </example>
        /// <param name="senderAddress">From address (i.e. [email protected]).</param>
        /// <param name="senderName">From name (i.e. Joe).</param>
        /// <param name="recipient">To address(es), separated by commas.</param>
        /// <param name="ccList">Comma-separated list of e-mail addresses for carbon copies.</param>
        /// <param name="bccList">Comma-separated list of e-mail addresses for blind carbon copies.</param>
        /// <param name="subject">Message subject.</param>
        /// <param name="body">Message body.</param>
        /// <param name="BodyFormat">MailFormat value.</param>
        /// <param name="attachments">ArrayList object with virtual paths to files.</param>
        /// <returns>"SUCCESS", or an error message.</returns>
        public static String Send(String senderAddress, String senderName, String recipient, String ccList, String bccList, String subject, String body, MailFormat BodyFormat, ArrayList attachments)
        {
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

            if (String.IsNullOrEmpty(senderName))
            {
                mail.From = new MailAddress(senderAddress);
            }

            else
            {
                mail.From = new MailAddress(senderAddress, senderName);
            }

            mail.Subject = subject;
            mail.Body = body;

            foreach (String address in recipient.Split(',')) mail.To.Add(address);

            if (!String.IsNullOrEmpty(ccList))
            {
                foreach (String address in ccList.Split(',')) mail.CC.Add(address);
            }

            if (!String.IsNullOrEmpty(bccList))
            {
                foreach (String address in bccList.Split(',')) mail.Bcc.Add(address);
            }

            String result = "SUCCESS";

            AlternateView newBody = AlternateView.CreateAlternateViewFromString(
                            body,
                            Encoding.ASCII,
                            "text/plain");

            try
            {
                mail.IsBodyHtml = (BodyFormat == MailFormat.HTML ? true : false);

                if (BodyFormat == MailFormat.PlainText7Bit)
                {
                    mail.Body = null;
                    newBody.TransferEncoding = TransferEncoding.SevenBit;
                    mail.AlternateViews.Add(newBody);
                }

                if (attachments != null)
                {
                    if (attachments.Count > 0)
                    {
                        foreach (String attachment in attachments)
                        {
                            System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(attachment, MediaTypeNames.Application.Octet);
                            mail.Attachments.Add(data);
                        }
                    }
                }

                SmtpClient smtp = new SmtpClient();

                smtp.Host = _emailServer;
                smtp.Port = 25;
                smtp.Credentials = new System.Net.NetworkCredential(_emailAuthAccount, _emailAuthPassword);
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.EnableSsl = MailUseSSL;

                smtp.Send(mail);

                if (newBody != null)
                {
                    newBody.Dispose();
                }

                mail.Dispose();
            }

            catch (Exception err)
            {
                result = err.ToString();
            }

            return result;
        }
Example #38
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)
        {
            //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;
            mailMessage = new MailMessage { From = new MailAddress(mailFrom) };
            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));
            }

            return SendMailInternal(mailMessage, subject, body, priority, bodyFormat, bodyEncoding,
                attachments, smtpServer, smtpAuthentication, smtpUsername,smtpPassword, smtpEnableSSL);
        }
Example #39
0
 public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body,
                               string[] attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL)
 {
     return SendMail(mailFrom,
                     mailTo,
                     cc,
                     bcc,
                     mailFrom,
                     priority,
                     subject,
                     bodyFormat,
                     bodyEncoding,
                     body,
                     attachments,
                     smtpServer,
                     smtpAuthentication,
                     smtpUsername,
                     smtpPassword,
                     smtpEnableSSL);
 }
Example #40
0
		public Mail(string to, string from, string message, string subject, string cc, string bcc, AttachmentCollection attachments, MailFormat format, string alternativeMessage) : this(to, from, message, subject, cc, bcc, null, null, false, alternativeMessage, attachments, format) { }
Example #41
0
		public Mail(string to, string from, string message, string subject, MailFormat format, string alternativeMessage) : this(to, from, message, subject, null, null, null, null, false, alternativeMessage, null, format) { }
Example #42
0
		public Mail(string to, string from, string message, string subject, string cc, MailFormat format) : this(to, from, message, subject, cc, null, null, null, false, null, null, format) { }
Example #43
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, 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);
        }
Example #44
0
		public Mail(MailAddress to, MailAddress from, string message, string subject, MailAddressCollection cc, MailAddressCollection bcc, MailAddress replyTo, MailAddress sender, bool senderHidden, string alternativeMessage, AttachmentCollection attachments, MailFormat format)
			: this(null as MailAddressCollection, from, message, subject, cc, bcc, replyTo, sender, senderHidden, alternativeMessage, attachments, format) {
			if(to != null) {
				this.to = new MailAddressCollection(to);
			}
		}
Example #45
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;
        }
Example #46
0
		public Mail(MailAddressCollection to, MailAddress from, string message, string subject, AttachmentCollection attachments, MailFormat format) : this(to, from, message, subject, null, null, null, null, false, null, attachments, format) { }
Example #47
0
 /// <summary>
 /// Send an e-mail message with optional attachments.
 /// </summary>
 /// <example>
 /// <code>
 /// using Mezzocode.Halide3;
 /// ...
 /// ArrayList AttachMe = new ArrayList();
 /// AttachMe.Add("/ftp/file1.pdf");
 /// AttachMe.Add("/ftp/file2.pdf");
 /// 
 /// string result = h3Email.Send(
 ///		"*****@*****.**",
 ///		"John Sender",
 ///		"[email protected],[email protected]",
 ///		"Message subject here",
 ///		"This is the message body.",
 ///		h3Email.MailFormat.PlainText,
 ///		AttachMe);
 /// </code>
 /// </example>
 /// <param name="senderAddress">From address (i.e. [email protected]).</param>
 /// <param name="senderName">From name (i.e. Joe).</param>
 /// <param name="recipient">To address(es), separated by commas.</param>
 /// <param name="subject">Message subject.</param>
 /// <param name="body">Message body.</param>
 /// <param name="BodyFormat">MailFormat value.</param>
 /// <param name="attachments">ArrayList object with virtual paths to files.</param>
 /// <returns>"SUCCESS", or an error message.</returns>
 public static String Send(string senderAddress, string senderName, string recipient, string subject, string body, MailFormat BodyFormat, ArrayList attachments)
 {
     return Send(senderAddress, senderName, recipient, "", "", subject, body, BodyFormat, attachments);
 }
Example #48
0
		public Mail(MailAddressCollection to, MailAddress from, string message, string subject, MailAddressCollection cc, MailFormat format) : this(to, from, message, subject, cc, null, null, null, false, null, null, format) { }
Example #49
0
 /// <summary>
 /// Send an e-mail message.
 /// </summary>
 /// <example>
 /// <code>
 /// using Mezzocode.Halide3;
 /// ...
 /// string result = h3Email.Send(
 ///		"*****@*****.**",
 ///		"John Sender",
 ///		"[email protected],[email protected]",
 ///		"[email protected],[email protected]",
 ///		"[email protected],[email protected]",
 ///		"Message subject here",
 ///		"This is the message body.",
 ///		h3Email.MailFormat.PlainText);
 /// </code>
 /// </example>
 /// <param name="sender">From address (i.e. [email protected]).</param>
 /// <param name="senderName">From name (i.e. Joe Smith).</param>
 /// <param name="recipient">To address(es), separated by commas.</param>
 /// <param name="ccList">Comma-separated list of e-mail addresses for carbon copies.</param>
 /// <param name="bccList">Comma-separated list of e-mail addresses for blind carbon copies.</param>
 /// <param name="subject">Message subject.</param>
 /// <param name="body">Message body.</param>
 /// <param name="BodyFormat">MailFormat value.</param>
 /// <returns>"SUCCESS", or an error message.</returns>
 public static String Send(string sender, string senderName, string recipient, string ccList, string bccList, string subject, string body, MailFormat BodyFormat)
 {
     ArrayList attachments = new ArrayList();
     return Send(sender, senderName, recipient, ccList, bccList, subject, body, BodyFormat, attachments);
 }
Example #50
0
		public Mail(MailAddressCollection to, MailAddress from, string message, string subject, MailFormat format, string alternativeMessage) : this(to, from, message, subject, null, null, null, null, false, alternativeMessage, null, format) { }
Example #51
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);

            //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();
                        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);
        }
Example #52
0
		public Mail(MailAddressCollection to, MailAddress from, string message, string subject, MailAddressCollection cc, MailAddressCollection bcc, AttachmentCollection attachments, MailFormat format, string alternativeMessage) : this(to, from, message, subject, cc, bcc, null, null, false, alternativeMessage, attachments, format) { }
Example #53
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));
        }
Example #54
0
        ///////////////////////////////////////////////////////////////////////
        public static string send_email(
            string to,
            string from,
            string cc,
            string subject,
            string body,
            MailFormat body_format,
            MailPriority priority,
            int[] attachment_bpids,
            bool return_receipt)
        {

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

            msg.From = new MailAddress(from);

            Email.add_addresses_to_email(msg, to, AddrType.to);

            if (!string.IsNullOrEmpty(cc.Trim()))
            {
                Email.add_addresses_to_email(msg, cc, AddrType.cc);
            }

            msg.Subject = subject;

            if (priority == MailPriority.Normal)
                msg.Priority = System.Net.Mail.MailPriority.Normal;
            else if (priority == MailPriority.High)
                msg.Priority = System.Net.Mail.MailPriority.High;
            else
                priority = MailPriority.Low;

            // This fixes a bug for a couple people, but make it configurable, just in case.
            if (Util.get_setting("BodyEncodingUTF8", "1") == "1")
            {
                msg.BodyEncoding = Encoding.UTF8;
            }


            if (return_receipt)
            {
                msg.Headers.Add("Disposition-Notification-To", from);
            }

            // workaround for a bug I don't understand...
            if (Util.get_setting("SmtpForceReplaceOfBareLineFeeds", "0") == "1")
            {
                body = body.Replace("\n", "\r\n");
            }

            msg.Body = body;
            msg.IsBodyHtml = body_format == MailFormat.Html;

            StuffToDelete stuff_to_delete = null;

            if (attachment_bpids != null && attachment_bpids.Length > 0)
            {
                stuff_to_delete = new StuffToDelete();

                string upload_folder = btnet.Util.get_upload_folder();

                if (string.IsNullOrEmpty(upload_folder))
                {
                    upload_folder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                    Directory.CreateDirectory(upload_folder);
                    stuff_to_delete.directories_to_delete.Add(upload_folder);
                }

                foreach (int attachment_bpid in attachment_bpids)
                {

                    string dest_path_and_filename = convert_uploaded_blob_to_flat_file(upload_folder, attachment_bpid, stuff_to_delete.files_to_delete);

                    // Add saved file as attachment
                    System.Net.Mail.Attachment mail_attachment = new System.Net.Mail.Attachment(
                        dest_path_and_filename);

                    msg.Attachments.Add(mail_attachment);

                }
            }

            try
            {
                // This fixes a bug for some people.  Not sure how it happens....
                msg.Body = msg.Body.Replace(Convert.ToChar(0), ' ').Trim();

                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();


                // SSL or not
                string force_ssl = Util.get_setting("SmtpForceSsl", "");

                if (force_ssl == "")
                {

                    // get the port so that we can guess whether SSL or not
                    System.Net.Configuration.SmtpSection smtpSec = (System.Net.Configuration.SmtpSection)
                        System.Configuration.ConfigurationManager.GetSection("system.net/mailSettings/smtp");

                    if (smtpSec.Network.Port == 465
                    || smtpSec.Network.Port == 587)
                    {
                        smtpClient.EnableSsl = true;
                    }
                    else
                    {
                        smtpClient.EnableSsl = false;
                    }
                }
                else
                {
                    if (force_ssl == "1")
                    {
                        smtpClient.EnableSsl = true;
                    }
                    else
                    {
                        smtpClient.EnableSsl = false;
                    }
                }

                // Ignore certificate errors
                if (smtpClient.EnableSsl)
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
                }

                smtpClient.Send(msg);

                if (stuff_to_delete != null)
                {
                    stuff_to_delete.msg = msg;
                    delete_stuff(stuff_to_delete);
                }

                return "";

            }
            catch (Exception e)
            {
                Util.write_to_log("There was a problem sending email.   Check settings in Web.config.");
                Util.write_to_log("TO:" + to);
                Util.write_to_log("FROM:" + from);
                Util.write_to_log("SUBJECT:" + subject);
                Util.write_to_log(e.GetBaseException().Message.ToString());

                delete_stuff(stuff_to_delete);

                return (e.GetBaseException().Message);
            }

        }
Example #55
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, ICollection <MailAttachment> attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL)
        {
            var smtpInfo = new SmtpInfo
            {
                Server         = smtpServer,
                Authentication = smtpAuthentication,
                Username       = smtpUsername,
                Password       = smtpPassword,
                EnableSSL      = smtpEnableSSL,
            };

            var mailInfo = new MailInfo
            {
                From         = mailFrom,
                Sender       = mailSender,
                To           = mailTo,
                CC           = cc,
                BCC          = bcc,
                ReplyTo      = replyTo,
                Priority     = priority,
                BodyEncoding = bodyEncoding,
                BodyFormat   = bodyFormat,
                Body         = body,
                Subject      = subject,
                Attachments  = attachments,
            };

            if (PortalSettings.Current != null && UserController.GetUserByEmail(PortalSettings.Current.PortalId, mailFrom) != null)
            {
                mailInfo.FromName = UserController.GetUserByEmail(PortalSettings.Current.PortalId, mailFrom).DisplayName;
            }

            return(MailProvider.Instance().SendMail(mailInfo, smtpInfo));
        }
Example #56
0
 public static string SendNotification(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)
 {
     return Mail.SendMail(MailFrom, MailTo, Cc, Bcc, Priority, Subject, BodyFormat, BodyEncoding, Body, Attachment, SMTPServer, SMTPAuthentication, SMTPUsername, SMTPPassword);
 }
Example #57
0
        ///////////////////////////////////////////////////////////////////////
        public static string send_email(
            string to,
            string from,
            string cc,
            string subject,
            string body,
            MailFormat body_format,
            MailPriority priority,
            int[] attachment_bpids,
            bool return_receipt)
        {
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

            msg.From = new MailAddress(from);

            Email.add_addresses_to_email(msg, to, AddrType.to);

            if (!string.IsNullOrEmpty(cc.Trim()))
            {
                Email.add_addresses_to_email(msg, cc, AddrType.cc);
            }

            msg.Subject = subject;

            if (priority == MailPriority.Normal)
            {
                msg.Priority = System.Net.Mail.MailPriority.Normal;
            }
            else if (priority == MailPriority.High)
            {
                msg.Priority = System.Net.Mail.MailPriority.High;
            }
            else
            {
                priority = MailPriority.Low;
            }

            // This fixes a bug for a couple people, but make it configurable, just in case.
            if (Util.get_setting("BodyEncodingUTF8", "1") == "1")
            {
                msg.BodyEncoding = Encoding.UTF8;
            }


            if (return_receipt)
            {
                msg.Headers.Add("Disposition-Notification-To", from);
            }

            // workaround for a bug I don't understand...
            if (Util.get_setting("SmtpForceReplaceOfBareLineFeeds", "0") == "1")
            {
                body = body.Replace("\n", "\r\n");
            }

            msg.Body       = body;
            msg.IsBodyHtml = body_format == MailFormat.Html;

            StuffToDelete stuff_to_delete = null;

            if (attachment_bpids != null && attachment_bpids.Length > 0)
            {
                stuff_to_delete = new StuffToDelete();

                string upload_folder = btnet.Util.get_upload_folder();

                if (string.IsNullOrEmpty(upload_folder))
                {
                    upload_folder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                    Directory.CreateDirectory(upload_folder);
                    stuff_to_delete.directories_to_delete.Add(upload_folder);
                }

                foreach (int attachment_bpid in attachment_bpids)
                {
                    string dest_path_and_filename = convert_uploaded_blob_to_flat_file(upload_folder, attachment_bpid, stuff_to_delete.files_to_delete);

                    // Add saved file as attachment
                    System.Net.Mail.Attachment mail_attachment = new System.Net.Mail.Attachment(
                        dest_path_and_filename);

                    msg.Attachments.Add(mail_attachment);
                }
            }

            try
            {
                // This fixes a bug for some people.  Not sure how it happens....
                msg.Body = msg.Body.Replace(Convert.ToChar(0), ' ').Trim();

                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();


                // SSL or not
                string force_ssl = Util.get_setting("SmtpForceSsl", "");

                if (force_ssl == "")
                {
                    // get the port so that we can guess whether SSL or not
                    System.Net.Configuration.SmtpSection smtpSec = (System.Net.Configuration.SmtpSection)
                                                                   System.Configuration.ConfigurationManager.GetSection("system.net/mailSettings/smtp");

                    if (smtpSec.Network.Port == 465 ||
                        smtpSec.Network.Port == 587)
                    {
                        smtpClient.EnableSsl = true;
                    }
                    else
                    {
                        smtpClient.EnableSsl = false;
                    }
                }
                else
                {
                    if (force_ssl == "1")
                    {
                        smtpClient.EnableSsl = true;
                    }
                    else
                    {
                        smtpClient.EnableSsl = false;
                    }
                }

                // Ignore certificate errors
                if (smtpClient.EnableSsl)
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };
                }

                smtpClient.Send(msg);

                if (stuff_to_delete != null)
                {
                    stuff_to_delete.msg = msg;
                    delete_stuff(stuff_to_delete);
                }

                return("");
            }
            catch (Exception e)
            {
                Util.write_to_log("There was a problem sending email.   Check settings in Web.config.");
                Util.write_to_log("TO:" + to);
                Util.write_to_log("FROM:" + from);
                Util.write_to_log("SUBJECT:" + subject);
                Util.write_to_log(e.GetBaseException().Message.ToString());

                delete_stuff(stuff_to_delete);

                return(e.GetBaseException().Message);
            }
        }
 private CodeStatement BuildFormatAssignment(MailFormat format)
 {
     CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression("mailMessage");
     CodePropertyReferenceExpression left = new CodePropertyReferenceExpression(targetObject, "BodyFormat");
     CodeTypeReferenceExpression expression3 = new CodeTypeReferenceExpression(typeof(MailFormat));
     string fieldName = "Text";
     if (format == MailFormat.Html)
     {
         fieldName = "Html";
     }
     return new CodeAssignStatement(left, new CodeFieldReferenceExpression(expression3, fieldName));
 }
        private string _Subject; //主题

        #endregion Fields

        #region Constructors

        public MailMessage()
        {
            _Recipients = new ArrayList();//收件人列表
            _Attachments = new MailAttachments();//附件
            _BodyFormat = MailFormat.HTML;//缺省的邮件格式为HTML
            _Priority = MailPriority.Normal;
            _Charset = "GB2312";
        }
Example #60
0
        public static string SendMail(string MailFrom, string MailTo, string Cc, string Bcc, string ReplyTo, MailPriority Priority, string Subject, MailFormat BodyFormat, System.Text.Encoding BodyEncoding, string Body,
        List<Attachment> Attachments, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword, bool SMTPEnableSSL)
        {
            string retValue = "";
            if (!IsValidEmailAddress(MailFrom, PortalSettings.Current != null ? PortalSettings.Current.PortalId : Null.NullInteger))
            {
                ArgumentException ex = new ArgumentException(string.Format(Localization.Localization.GetString("EXCEPTION_InvalidEmailAddress", PortalSettings.Current), MailFrom));
                Exceptions.Exceptions.LogException(ex);
                return ex.Message;
            }

            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;
            }
            MailTo = MailTo.Replace(";", ",");
            Cc = Cc.Replace(";", ",");
            Bcc = Bcc.Replace(";", ",");
            System.Net.Mail.MailMessage objMail = null;
            try
            {
                objMail = new System.Net.Mail.MailMessage();
                objMail.From = new MailAddress(MailFrom);
                if (!String.IsNullOrEmpty(MailTo))
                {
                    objMail.To.Add(MailTo);
                }
                if (!String.IsNullOrEmpty(Cc))
                {
                    objMail.CC.Add(Cc);
                }
                if (!String.IsNullOrEmpty(Bcc))
                {
                    objMail.Bcc.Add(Bcc);
                }
                if (ReplyTo != string.Empty)
                    objMail.ReplyTo = new System.Net.Mail.MailAddress(ReplyTo);
                objMail.Priority = (System.Net.Mail.MailPriority)Priority;
                objMail.IsBodyHtml = BodyFormat == MailFormat.Html;
                foreach (Attachment myAtt in Attachments)
                {
                    objMail.Attachments.Add(myAtt);
                }
                objMail.SubjectEncoding = BodyEncoding;
                objMail.Subject = HtmlUtils.StripWhiteSpace(Subject, true);
                objMail.BodyEncoding = BodyEncoding;
                System.Net.Mail.AlternateView PlainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(ConvertToText(Body), null, "text/plain");
                objMail.AlternateViews.Add(PlainView);
                if (HtmlUtils.IsHtml(Body))
                {
                    System.Net.Mail.AlternateView HTMLView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html");
                    objMail.AlternateViews.Add(HTMLView);
                }
            }
            catch (Exception objException)
            {
                retValue = MailTo + ": " + objException.Message;
                Exceptions.Exceptions.LogException(objException);
            }
            if (objMail != null)
            {
                int SmtpPort = Null.NullInteger;
                int portPos = SMTPServer.IndexOf(":");
                if (portPos > -1)
                {
                    SmtpPort = Int32.Parse(SMTPServer.Substring(portPos + 1, SMTPServer.Length - portPos - 1));
                    SMTPServer = SMTPServer.Substring(0, portPos);
                }
                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
                try
                {
                    if (!String.IsNullOrEmpty(SMTPServer))
                    {
                        smtpClient.Host = SMTPServer;
                        if (SmtpPort > Null.NullInteger)
                        {
                            smtpClient.Port = SmtpPort;
                        }
                        switch (SMTPAuthentication)
                        {
                            case "":
                            case "0":
                                break;
                            case "1":
                                if (!String.IsNullOrEmpty(SMTPUsername) && !String.IsNullOrEmpty(SMTPPassword))
                                {
                                    smtpClient.UseDefaultCredentials = false;
                                    smtpClient.Credentials = new System.Net.NetworkCredential(SMTPUsername, SMTPPassword);
                                }
                                break;
                            case "2":
                                smtpClient.UseDefaultCredentials = true;
                                break;
                        }
                    }
                    smtpClient.EnableSsl = SMTPEnableSSL;
                    smtpClient.Send(objMail);
                    retValue = "";
                }
                catch (SmtpFailedRecipientException exc)
                {
                    retValue = string.Format(Localization.Localization.GetString("FailedRecipient"), exc.FailedRecipient);
                    Exceptions.Exceptions.LogException(exc);
                }
                catch (SmtpException exc)
                {
                    retValue = Localization.Localization.GetString("SMTPConfigurationProblem");
                    Exceptions.Exceptions.LogException(exc);
                }
                catch (Exception objException)
                {
                    if (objException.InnerException != null)
                    {
                        retValue = string.Concat(objException.Message, Environment.NewLine, objException.InnerException.Message);
                        Exceptions.Exceptions.LogException(objException.InnerException);
                    }
                    else
                    {
                        retValue = objException.Message;
                        Exceptions.Exceptions.LogException(objException);
                    }
                }
                finally
                {
                    objMail.Dispose();
                }
            }
            return retValue;
        }