Пример #1
0
 public bool SendMultiPartEmail(string sender, string recipients, string subject, string textBody, string htmlBody)
 {
     try
     {
         if (!bSMTPInitialized)
         {
             throw new Exception("Error: SMTP Not initialized");
         }
         // Initialize the message with the plain text body:
         MailMessage msg = new MailMessage(sender, recipients, subject, textBody);
         // Convert the html body to a memory stream:
         Byte[]       bytes      = System.Text.Encoding.UTF8.GetBytes(htmlBody);
         MemoryStream htmlStream = new MemoryStream(bytes);
         // Add the HTML body to the message:
         AlternateView htmlView = new AlternateView(htmlStream, MediaTypeNames.Text.Html);
         msg.AlternateViews.Add(htmlView);
         // Ship it!
         emailClient.Send(msg);
         htmlView.Dispose();
         htmlStream.Dispose();
         return(true);
     }
     catch (Exception ex)
     {
         _logger.LogItem("EmailService SendMultiPartEmail() To " + recipients + " - email send failed: " + ex.Message);
         return(false);
     }
 }
 public bool SendMultiPartEmail(HtmlEmailStruct htmlEmailStruct)
 {
     try
     {
         if (!bSMTPInitialized)
         {
             throw new Exception("Error: SMTP Not initialized");
         }
         // Initialize the message with the plain text body:
         MailMessage msg = new MailMessage(htmlEmailStruct.SenderEmail, htmlEmailStruct.ReceiverEmail, htmlEmailStruct.EmailTitle, htmlEmailStruct.EmailBody);
         // Convert the html body to a memory stream:
         Byte[]       bytes      = System.Text.Encoding.UTF8.GetBytes(htmlEmailStruct.HTMLBody);
         MemoryStream htmlStream = new MemoryStream(bytes);
         // Add the HTML body to the message:
         AlternateView htmlView = new AlternateView(htmlStream, MediaTypeNames.Text.Html);
         msg.AlternateViews.Add(htmlView);
         // Ship it!
         emailClient.Send(msg);
         htmlView.Dispose();
         htmlStream.Dispose();
         return(true);
     }
     catch (Exception ex)
     {
         //Log("EmailService (SendMultiPartEmail) - email send failed: " + ex.Message);
         return(false);
     }
 }
Пример #3
0
        //</snippet4>

        //<snippet5>
        public static void CreateMessageWithMultipleViews(string server, string recipients)
        {
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
                "*****@*****.**",
                recipients,
                "This email message has multiple views.",
                "This is some plain text.");

            // Construct the alternate body as HTML.
            string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";

            body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
            body += "</HEAD><BODY><DIV><FONT face=Arial color=#ff0000 size=2>this is some HTML text";
            body += "</FONT></DIV></BODY></HTML>";

            ContentType mimeType = new System.Net.Mime.ContentType("text/html");
            // Add the alternate body to the message.

            AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);

            message.AlternateViews.Add(alternate);

            // Send the message.
            SmtpClient client = new SmtpClient(server);

            client.Credentials = CredentialCache.DefaultNetworkCredentials;

            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught in CreateMessageWithMultipleViews(): {0}",
                                  ex.ToString());
            }
            // Display the values in the ContentType for the attachment.
            ContentType c = alternate.ContentType;

            Console.WriteLine("Content type");
            Console.WriteLine(c.ToString());
            Console.WriteLine("Boundary {0}", c.Boundary);
            Console.WriteLine("CharSet {0}", c.CharSet);
            Console.WriteLine("MediaType {0}", c.MediaType);
            Console.WriteLine("Name {0}", c.Name);
            Console.WriteLine("Parameters: {0}", c.Parameters.Count);
            foreach (DictionaryEntry d in c.Parameters)
            {
                Console.WriteLine("{0} = {1}", d.Key, d.Value);
            }
            Console.WriteLine();
            alternate.Dispose();
        }
Пример #4
0
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            long trick = DateTime.Now.Ticks;

            try
            {
                using (System.Net.Mail.SmtpClient client = new SmtpClient("smtp.qq.com"))
                {
                    client.UseDefaultCredentials = false;
                    client.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "lhw521zxh");
                    client.DeliveryMethod        = SmtpDeliveryMethod.Network;

                    MailAddress addressFrom = new MailAddress("*****@*****.**", "多媒体课件编辑器-意见反馈");
                    MailAddress addressTo   = new MailAddress("*****@*****.**", "多媒体课件编辑器-意见反馈");

                    using (System.Net.Mail.MailMessage message = new MailMessage(addressFrom, addressTo))
                    {
                        message.Sender       = new MailAddress("*****@*****.**");
                        message.BodyEncoding = System.Text.Encoding.UTF8;
                        message.IsBodyHtml   = true;
                        message.Subject      = DateTime.Now + "---" + "意见反馈";


                        SaveFrameworkElementToImage(this, trick + ".bmp");
                        Attachment     attcahment = new Attachment(trick + ".bmp");
                        LinkedResource linked     = new LinkedResource(trick + ".bmp", "image/gif");
                        linked.ContentId = "weblogo";
                        string        htmlBodyContent = GetHtmlContent("weblogo");
                        AlternateView htmlBody        = AlternateView.CreateAlternateViewFromString(htmlBodyContent, null, "text/html");

                        htmlBody.LinkedResources.Add(linked);
                        message.AlternateViews.Add(htmlBody);
                        client.Send(message);
                        MessageBox.Show("提交成功,非常感谢您的意见!");
                        attcahment.Dispose();
                        linked.Dispose();
                        htmlBody.Dispose();
                    }
                }
                File.Delete(trick + ".bmp");
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("提交失败!");
            }
        }
    /// <summary>
    /// Called once the sumbit button has been clicked
    /// In the end it will send an email if all the fields have been filled properly
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void bSend_Click(object sender, EventArgs e)
    {
        //checks if validation has passed
        if (IsValid)
        {
            //MailMessage class
            MailMessage mailmsg = new MailMessage();
            mailmsg.Subject    = this.Subject.Text;
            mailmsg.IsBodyHtml = true;

            LinkedResource image = new LinkedResource(Server.MapPath("~/image/business-company-logo-27438277.jpg"));

            string message = generateMessage(this.Msg.Text, this.Email.Text, this.Name.Text);
            string body    = string.Format(@"{0}
                                        <img style='height: 180px; width: 300px' src=""cid:{1}""/>"
                                           , message, image.ContentId);                                //'@' before the string used so that all of the backslash escapes in the file path.

            AlternateView view = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); //could have plain/text format version before this.
            view.LinkedResources.Add(image);
            mailmsg.AlternateViews.Add(view);                                                          //adds the AlternateView;


            string     filePath = ""; //string filePath to an empty string. when checking whether there is an uploaded file, there will be no need to check if the string object is null.
            FileUpload fileAtt  = this.fileUp;
            Attachment att      = null;
            if (fileAtt.HasFiles)
            {
                //if there is a uploaded file
                filePath = Server.MapPath("~/uploads/" + this.fileUp.FileName);
                fileAtt.SaveAs(filePath);
                att = new Attachment(filePath);
                mailmsg.Attachments.Add(att); //add the uploaded file as a attachment
            }

            mailmsg.From = new MailAddress("*****@*****.**", "Name Surname"); //the sender
            mailmsg.To.Add(new MailAddress("*****@*****.**", "Name Surname"));  //the receiver, could also add a carbon copy using "mailMessage.CC"

            SmtpClient sc = new SmtpClient();
            try
            {
                //most of this could be done in the Web.config file under system.net -> mailSettings tags
                sc.DeliveryMethod = SmtpDeliveryMethod.Network;
                sc.EnableSsl      = true;                                                //enables secure socket layer
                sc.Host           = "smtp.gmail.com";                                    //gmail
                sc.Port           = 25;                                                  //most will use port 25, it's best to check which port does the provider use
                sc.Credentials    = new NetworkCredential("*****@*****.**", "password"); //email and password for the sender, email provider may block it. There should be an option to allow less secure connections.
                sc.Send(mailmsg);                                                        //sends the email
            }
            catch (SmtpException smtpException)
            {
                System.Diagnostics.Debug.WriteLine("Email Provider may be blocking access"); //Email providors normally block it as this is a less secure connection (i.e the password is visible in the source code, refer to 'NetworkCredential' on line 76)
                System.Diagnostics.Debug.WriteLine(smtpException.Message);                   //There can be other causes so a message is also displayed
            }
            finally
            {
                //release resources used and delete uploaded file if it exists
                if (sc != null)
                {
                    sc.Dispose();
                }
                if (image != null)
                {
                    image.Dispose();
                }
                if (view != null)
                {
                    view.Dispose();
                }
                if (att != null)
                {
                    att.Dispose();
                }
                if (mailmsg != null)
                {
                    mailmsg.Dispose();
                }
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);                        //deletes uploaded file if it exists
                }
            }
        }
    }
Пример #6
0
        /// <summary><![CDATA[
        /// Send an email message with optional attachments.
        /// ]]></summary>
        /// <example>
        /// <code><![CDATA[
        /// ArrayList AttachMe = new ArrayList();
        /// AttachMe.Add("/ftp/file1.pdf");
        /// AttachMe.Add("/ftp/file2.pdf");
        ///
        /// string result = Mailer.Send(
        ///		"*****@*****.**",
        ///		"John Sender",
        ///		"[email protected],[email protected]",
        ///		"[email protected],[email protected]",
        ///		"[email protected],[email protected]",
        ///		"Message subject here",
        ///		"This is the message body.",
        ///		Mailer.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 email addresses for carbon copies.</param>
        /// <param name="bccList">Comma-separated list of email 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>
        /// <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, EmailFormat bodyFormat, ArrayList attachments, ArrayList attachmentNames)
        {
            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 == EmailFormat.Html ? true : false);

                if (bodyFormat == EmailFormat.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.Send(mail);

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

                mail.Dispose();
            }

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

            return(result);
        }
Пример #7
0
        public static void SendReportByEmail(string subject, string emailFrom, string emailPassword, string emailTo,
                                             string ccTo, string emailHost, int emailPort, bool enableSsl, string tempPath, DataTable dtResult, params string[] attachments)
        {
            List <string> imagefiles = new List <string>();

            StringBuilder sb = new StringBuilder(@"<style type='text/css'>
  th {background-color: #0099CC;color: white;}
  .fail {background-color: #FF6666;}
  .success {background-color: #99CC66;}
</style>");

            sb.Append("<table width='100%' border='1' cellpadding='0' cellspacing='0'><tr>");
            foreach (DataColumn dc in dtResult.Columns)
            {
                sb.AppendFormat("<th>{0}</th>", dc.ColumnName);
            }

            List <Attachment> lstAttachment = attachments == null ? new List <Attachment>() : attachments.Select(attachFilePath => new Attachment(attachFilePath)).ToList();

            foreach (DataRow dr in dtResult.Rows)
            {
                if (!DBNull.Value.Equals(dr["Image"]) && !string.IsNullOrEmpty(dr["Image"].ToString()))
                {
                    string imageHtml = string.Empty;
                    foreach (string errImage in dr["Image"].ToString().Split(';'))
                    {
                        if (string.IsNullOrEmpty(errImage))
                        {
                            continue;
                        }
                        Attachment attachImage = new Attachment(errImage, "image/png");
                        attachImage.Name = Path.GetFileNameWithoutExtension(errImage);
                        imageHtml       += string.Format("<img src=\"cid:{0}\">", attachImage.ContentId);
                        lstAttachment.Add(attachImage);
                        imagefiles.Add(errImage);
                    }
                    dr["Image"] = imageHtml;
                    sb.Append("</tr><tr class='fail'>");
                }
                else if (dr["Result"].Equals("Passed"))
                {
                    sb.Append("</tr><tr class='success'>");
                }
                else
                {
                    sb.Append("</tr><tr>");
                }

                foreach (DataColumn dc in dtResult.Columns)
                {
                    sb.AppendFormat("<td>{0}</td>", dr[dc]);
                }
            }
            sb.Append("</tr></table>");


            MailMessage   mailMessage = null;
            AlternateView htmlBody    = null;
            SmtpClient    client      = null;

            try
            {
                mailMessage      = new MailMessage();
                mailMessage.From = new MailAddress(emailFrom);
                foreach (string toemail in emailTo.Split(';'))
                {
                    mailMessage.To.Add(toemail);
                }
                if (!string.IsNullOrEmpty(ccTo))
                {
                    foreach (string ccemail in ccTo.Split(';'))
                    {
                        mailMessage.CC.Add(ccemail);
                    }
                }
                mailMessage.Subject = subject;
                htmlBody            = AlternateView.CreateAlternateViewFromString(sb.ToString(), null,
                                                                                  "text/html");
                foreach (var image in lstAttachment)
                {
                    mailMessage.Attachments.Add(image);
                }
                mailMessage.AlternateViews.Add(htmlBody);
                client = new SmtpClient(emailHost, emailPort);

                client.Credentials = new System.Net.NetworkCredential(emailFrom, emailPassword);
                client.EnableSsl   = enableSsl;
                client.Send(mailMessage);
            }
            catch (SmtpException ex)
            {
                throw new Exception("Email error, detail information:" + ex.Message);
            }
            finally
            {
                if (client != null)
                {
                    client.Dispose();
                }
                if (htmlBody != null)
                {
                    htmlBody.Dispose();
                }
                if (mailMessage != null)
                {
                    mailMessage.Dispose();
                }
            }
        }
 public void Dispose()
 {
     m_alternateView.Dispose();
 }