Example #1
2
        public static void SendMail(IEmailAccountSettingsProvider provider, string to, string subject, string body, Attachment attach, AlternateView av, bool isHTML)
        {
            if (provider.SmtpFrom != String.Empty)
            {
                if (provider.SmtpHost == "") return;
                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress(provider.SmtpFrom);
                mailMessage.To.Add(to);
                mailMessage.Subject = subject;
                if (av != null)
                    mailMessage.AlternateViews.Add(av);
                mailMessage.BodyEncoding = Encoding.UTF8;
                mailMessage.Body = body;

                if (attach != null)
                    mailMessage.Attachments.Add(attach);
                if (isHTML)
                    mailMessage.IsBodyHtml = true;

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Host = provider.SmtpHost;
                smtpClient.Port = Convert.ToInt32(provider.SmtpPort);
                smtpClient.UseDefaultCredentials = Convert.ToBoolean(provider.SmtpCredentials);
                smtpClient.Credentials = new NetworkCredential(provider.SmtpUser, provider.SmtpPwd);
                smtpClient.EnableSsl = Convert.ToBoolean(provider.SmtpSSL);
                smtpClient.Send(mailMessage);
            }
        }
Example #2
0
        public void SendMail(string smtpServer, string emailTo, string emailFrom, string password, string subject, string body, string fileLocation)
        {
            var fromAddress = new MailAddress(emailFrom, emailFrom);
            var toAddress = new MailAddress(emailTo, emailTo);
            var attachment = new Attachment(fileLocation);

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, password)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body,
            })
            {
                message.Attachments.Add(attachment);
                smtp.Send(message);
            }
        }
 protected void Button1_Click(object sender, EventArgs e)
 {            
     DataView DV1 = (DataView)AccessDataSource1.Select(DataSourceSelectArguments.Empty);
     foreach (DataRowView DRV1 in DV1)
     {
         string ToAddress = DRV1["Email_Address"].ToString();
         MailMessage message = new MailMessage("*****@*****.**", ToAddress);                
         message.Body = TextBox2.Text;
         message.Subject = TextBox1.Text;
         message.BodyEncoding = System.Text.Encoding.UTF8;
         string Path = HttpContext.Current.Server.MapPath("~/images/EnewsLetters/Temp/");
         FileUpload1.SaveAs(Path + FileUpload1.FileName);
         Attachment attach1 = new Attachment(Path + FileUpload1.FileName);
         message.Attachments.Add(attach1);
         SmtpClient mailserver = new SmtpClient("amcsmail02.amcs.com", 25);
         try
         {
             mailserver.Send(message);
         }
         catch
         {
         }
         attach1.Dispose();
     }
     System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/images/EnewsLetters/Temp/") + FileUpload1.FileName);
     TextBox1.Text = "";
     TextBox2.Text = "";
 }
Example #4
0
        ///<summary>
        /// 添加附件
        ///</summary>
        ///<param name="attachPaths">附件的路径集合,以分号分隔</param>
        public bool AddAttachments(string attachPaths)
        {
            bool isSuccess = true;
            try
            {
                string[] paths = attachPaths.Split(';'); //以什么符号分隔可以自定义
                Attachment attachment;
                ContentDisposition disposition;
                foreach (string path in paths)
                {
                    if (!File.Exists(path))
                        continue;
                    attachment = new Attachment(path, MediaTypeNames.Application.Octet);
                    attachment.Name = System.IO.Path.GetFileName(path);
                    attachment.NameEncoding = System.Text.Encoding.GetEncoding("gb2312");
                    attachment.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
                    disposition = attachment.ContentDisposition;
                    disposition.Inline = true;
                    disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Inline;
                    disposition.CreationDate = File.GetCreationTime(path);
                    disposition.ModificationDate = File.GetLastWriteTime(path);
                    disposition.ReadDate = File.GetLastAccessTime(path);
                    this.m_mail.Attachments.Add(attachment);
                }
            }
            catch (Exception)
            {
                isSuccess = false;
            }

            return isSuccess;
        }
Example #5
0
        public void SendEmail(string strUserId, string strUserPwd, string strUserName, string strSubject, string strMailBody, string strFrom, string strTo, string strAttachmentpath)
        {
            //******************************
            // Method responsible for writing out the e-mail to be sent
            //******************************
            try
            {

                string server = System.Configuration.ConfigurationManager.AppSettings["MailConfig"];

                MailMessage mail = new MailMessage(strFrom.ToString(), strTo.ToString());
                if (strAttachmentpath != "" && strAttachmentpath != null)
                {
                    Attachment attachFile = new Attachment(strAttachmentpath);
                    mail.Attachments.Add(attachFile);
                }
                mail.Subject = strSubject;
                mail.Body = strMailBody;
                mail.IsBodyHtml = true;
                smtpClientObj = new SmtpClient(smtpServer);
                //smtpClientObj.Host = "localhost";
                smtpClientObj.Port = 25;
                smtpClientObj.Send(mail);

            }
            catch (SmtpException smtpex)
            {
                HttpContext.Current.Session["ErrorMessage"] = "The following error has occured on the page : " + smtpex.Message.ToString();
            }
            catch (Exception ex)
            {
                HttpContext.Current.Session["ErrorMessage"] = "The following error has occured on the page : " + ex.Message.ToString();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                mail = new MailMessage();
                SmtpServer = new SmtpClient("smtp.yourdomain.com");
                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add(combo.Items[combo.SelectedIndex].ToString());
                mail.Subject = subjbox.Text.ToString();
                mail.Body = msgbox.Text.ToString();
                if (strFileName != string.Empty)
                {
                    System.Net.Mail.Attachment attachment;
                    attachment = new System.Net.Mail.Attachment(strFileName);
                    mail.Attachments.Add(attachment);

                    SmtpServer.Send(mail);
                    MessageBox.Show("Sent Message With Attachment", "MMS by Paul");
                }

                else {
                    SmtpServer.Send(mail);
                    MessageBox.Show("Sent Message", "MMS by Paul");
                     }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Example #7
0
        public void enviarCorreo(string emisor, string password, string mensaje, string asunto, string destinatario, string ruta)
        {
            try
            {
                correos.To.Clear();
                correos.Body = "";
                correos.Subject = "";
                correos.Body = mensaje;
                correos.Subject = asunto;
                correos.IsBodyHtml = true;
                correos.To.Add(destinatario.Trim());

                if (ruta.Equals("") == false)
                {
                    System.Net.Mail.Attachment archivo = new System.Net.Mail.Attachment(ruta);
                    correos.Attachments.Add(archivo);
                }

                correos.From = new MailAddress(emisor);
                envios.Credentials = new NetworkCredential(emisor, password);

                //Datos importantes no modificables para tener acceso a las cuentas

                envios.Host = "smtp.gmail.com";
                envios.Port = 587;
                envios.EnableSsl = true;

                envios.Send(correos);
                MessageBox.Show("El mensaje fue enviado correctamente");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "No se envio el correo correctamente", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 public void Attach(string[] FileNames)
 {
     Array.ForEach(FileNames, (x) => {
         Attachment att = new Attachment(x);
         emailMess.Attachments.Add(att);
     });
 }
Example #9
0
 private static Attachment AddInlineAttachment(string FileName)
 {
     Attachment attchmnt = new Attachment(@"C:\Hariom\Personal\DotNetExperiments\TeamWorkManagement\ConsoleApplication6\ConsoleApplication6\ConsoleApplication6\" + FileName);
     attchmnt.ContentDisposition.Inline = true;
     attchmnt.ContentId = FileName.Substring(FileName.LastIndexOf("\\") + 1).Replace(".", "");
     return attchmnt;
 }
Example #10
0
		public AjaxReturn Email(int id) {
			Extended_Document header = prepareInvoice(id);
			NameAddress customer = Database.Get<NameAddress>((int)header.DocumentNameAddressId);
			Utils.Check(!string.IsNullOrEmpty(Settings.CompanyEmail), "Company has no email address");
			Utils.Check(!string.IsNullOrEmpty(customer.Email), "Customer has no email address");
			Utils.Check(customer.Email.Contains('@'), "Customer has an invalid email address");
			((JObject)((JObject)Record)["header"])["doctype"] = header.DocType.ToLower();
			((JObject)Record)["customer"] = customer.ToJToken();
			string text = LoadTemplate("customer/email.txt", this);
			string subject = Utils.NextToken(ref text, "\n").Trim();
			using (MemoryStream stream = new MemoryStream(Encoding.GetBytes(LoadTemplate("customer/print", this)))) {
				// Create a message and set up the recipients.
				MailMessage message = new MailMessage();
				message.From = new MailAddress(Settings.CompanyEmail);
				foreach(string e in customer.Email.Split(','))
					message.To.Add(e);
				message.Bcc.Add(Settings.CompanyEmail);
				message.Subject = subject;
				message.Body = text;
				// Create  the file attachment for this e-mail message.
				Attachment data = new Attachment(stream, Settings.CompanyName + "Invoice" + header.DocumentIdentifier + ".html", "text/html");
				// Add the file attachment to this e-mail message.
				message.Attachments.Add(data);

				//Send the message.
				SmtpClient client = new SmtpClient(Settings.MailServer);
				// Add credentials if the SMTP server requires them.
				client.Credentials = new NetworkCredential(Settings.MailUserName, Settings.MailPassword);
				client.Port = Settings.MailPort;
				client.EnableSsl = Settings.MailSSL;
				client.Send(message);
			}
			return new AjaxReturn() { message = "Email sent to " + customer.Email };
		}
        public static void SendEmail(string from, string[] toAddresses, string[] ccAddresses, string subject, string body, System.IO.Stream stream, string filename)
        {
            MailMessage EmailMsg = new MailMessage();
            EmailMsg.From = new MailAddress(from);
            for (int i = 0; i < toAddresses.Count(); i++)
            {
                EmailMsg.To.Add(new MailAddress(toAddresses[i]));
            }
            for (int i = 0; i < ccAddresses.Count(); i++)
            {
                EmailMsg.CC.Add(new MailAddress(ccAddresses[i]));
            }
            EmailMsg.Subject = subject;
            EmailMsg.Body = body;
            EmailMsg.IsBodyHtml = true;
            EmailMsg.Priority = MailPriority.Normal;

            System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("Application/pdf");

            Attachment a = new Attachment(stream, ct);
            a.Name = filename;

            EmailMsg.Attachments.Add(a);

            SmtpClient MailClient = new SmtpClient();
            MailClient.Send(EmailMsg);
        }
Example #12
0
        public static void Send(string server, string sender, string recipient, string subject,
    string body, bool isBodyHtml, Encoding encoding, bool isAuthentication, params string[] files)
        {
            SmtpClient smtpClient = new SmtpClient(server);
            MailMessage message = new MailMessage(sender, recipient);
            message.IsBodyHtml = isBodyHtml;

            message.SubjectEncoding = encoding;
            message.BodyEncoding = encoding;

            message.Subject = subject;
            message.Body = body;

            message.Attachments.Clear();
            if (files != null && files.Length != 0)
            {
                for (int i = 0; i < files.Length; ++i)
                {
                    Attachment attach = new Attachment(files[i]);
                    message.Attachments.Add(attach);
                }
            }

            if (isAuthentication == true)
            {
                smtpClient.Credentials = new NetworkCredential(SmtpConfig.Create().SmtpSetting.User,
                    SmtpConfig.Create().SmtpSetting.Password);
            }
            smtpClient.Send(message);
        }
        public Boolean Correo(String to, String sender, String from, String subject, String body, String pass, Attachment archivo)
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(from, sender);
            msg.To.Add(new MailAddress(to));
            msg.Subject = subject;
            msg.Body = body;
            msg.IsBodyHtml = true;

            if (archivo != null)
            {
                msg.Attachments.Add(archivo);
            }
            SmtpClient smtp = new SmtpClient();
            //smtp.Host = "smtp.mail.yahoo.com"; // yahoo
            //smtp.Host = "smtp.live.com"; // hotmail
            //smtp.Host = "localhost"; // servidor local
            smtp.Host = "smtp.gmail.com"; // gmail
            smtp.Port = 25;
            smtp.Credentials = new NetworkCredential(from, pass);
            smtp.EnableSsl = true;
            try
            {
                smtp.Send(msg);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
Example #14
0
    protected void SendMail()
    {
        var          fromAddress  = doctor.Email;
        var          toAddress    = work.GenericPatientRepo.GetByID(Convert.ToInt32(ddlPatient.SelectedValue)).Email;
        const string fromPassword = "";
        string       subject      = "Prescription from Doctor at " + DateTime.Now;
        string       body         = "Note: " + txtPrescription.Text + "\n";

        body += "Description: " + txtNote.Text + "\n";
        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment(Server.MapPath("Uploads/" + TextBox2.Text));
        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
        message.Attachments.Add(attachment);
        var smtp = new System.Net.Mail.SmtpClient();

        {
            smtp.Host           = "smtp.gmail.com";
            smtp.Port           = 587;
            smtp.EnableSsl      = true;
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtp.Credentials    = new System.Net.NetworkCredential(fromAddress, fromPassword);
            smtp.Timeout        = 20000;
        }
        // Passing values to smtp object
        smtp.Send(fromAddress, toAddress, subject, body);
    }
Example #15
0
		public virtual void SendEmail(EmailServerSettings settings, string subject, string body, IEnumerable<MailAddress> toAddressList, MailAddress fromAddress, params EmailAttachmentData[] attachments)
		{
			using (var smtpClient = GetSmtpClient(settings))
			{
				var message = new MailMessage();
				message.From = fromAddress;
				message.Body = body;
				message.Subject = subject;
				message.IsBodyHtml = true;
				foreach (var toAddress in toAddressList)
				{
					message.To.Add(toAddress);
				}

				if (attachments != null)
				{
					foreach (var item in attachments)
					{
						var stream = StreamHelper.CreateMemoryStream(item.AttachmentData);
						stream.Position = 0;

						var attachment = new Attachment(stream, item.FileName);

						message.Attachments.Add(attachment);
					}
				}

				smtpClient.Send(message);
			}
		}
Example #16
0
 public static bool EmailToAdvisor(string username, AdvisorModel advisor)
 {
     var document = PrintingHelper.PrintCappReport(username);
     if (document == null) return false;
     var email = new MailMessage("*****@*****.**", advisor.Email)
     {
         Subject = "CAPPamari - Please review " + username + "'s CAPP report",
         Body = "Dear " + advisor.Name + ",\n" +
                "\n" +
                "Please review my latest plan for fulfulling my graduation requirements.\n" +
                "\n" +
                "Sincerely,\n" +
                username + "\n" +
                "--\n" +
                HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)
     };
     using (var pdfStream = new MemoryStream())
     {
         document.SaveToStream(pdfStream);
         pdfStream.Position = 0;
         var attachment = new Attachment(pdfStream, new ContentType(MediaTypeNames.Application.Pdf));
         attachment.ContentDisposition.FileName = "CAPP Report.pdf";
         email.Attachments.Add(attachment);
         try
         {
             var smtpServer = new SmtpClient("localhost");
             smtpServer.Send(email);
         }
         catch
         {
             return false;
         }
         return true;
     }
 }
Example #17
0
    public static string SendEmailWithAttachement(string To, string from, string subject, string body, string host, int port, string AttachPath)
    {
        string result = "NOT SENT.";

        try
        {
            System.Net.Mail.SmtpClient  mc         = new System.Net.Mail.SmtpClient(host, port);
            System.Net.Mail.MailMessage msg        = new System.Net.Mail.MailMessage(from, To, subject, body);
            System.Net.Mail.Attachment  attachment = new System.Net.Mail.Attachment(AttachPath);
            msg.IsBodyHtml = true;
            msg.Attachments.Add(attachment);
            string userid;
            string password;
            userid         = ConfigurationManager.AppSettings["userid"].ToString();
            password       = ConfigurationManager.AppSettings["password"].ToString();
            mc.Credentials = new System.Net.NetworkCredential(userid, password);
            mc.Send(msg);
            result = "SENT.";
            msg.Attachments.Dispose();
            //if(File.Exists(AttachPath ) )
            //{
            //File.Delete(AttachPath);
            //}
        }
        catch (Exception ex)
        {
            result = ex.Message;
            //throw;
        }
        return(result);
    }
Example #18
0
        public ActionResult Index()
        {
            var outParam = new SqlParameter
            {
                ParameterName = "@result",
                Direction = ParameterDirection.Output,
                SqlDbType = SqlDbType.Int
            };

            List<Boolean> _BUEvent = db.Database.SqlQuery<Boolean>("sp_InsertIntoBuEventLog @result OUT", outParam).ToList();

            using (TransactionScope transaction = new TransactionScope())
            {

                bool result = _BUEvent.FirstOrDefault();
                if (result)
                {
                    var _vwSendEmail = (db.vwSendEmails.Where(a => a.CREATEDDATE == CurrentDate).Select(a => new { a.KDKC, a.email, a.NMKC,a.TAHUN,a.BULAN,a.MINGGU })).Distinct();
                    int count = 0;
                    foreach(var sending in _vwSendEmail)
                    {
                        MemoryStream memory = new MemoryStream();
                        PdfDocument document = new PdfDocument() { Url = string.Format("http://*****:*****@gmail.com", "Legal-InHealth Reminder ");
                        message.Subject = SubjectName;
                        message.Attachments.Add(data);
                        message.Body = sending.NMKC;
                        SmtpClient client = new SmtpClient();

                        try
                        {
                            client.Send(message);
                        }
                        catch (Exception ex)
                        {

                            ViewData["SendingException"] = string.Format("Exception caught in SendErrorLog: {0}",ex.ToString());
                            return View("ErrorSending", ViewData["SendingException"]);
                        }
                        data.Dispose();
                        // Close the log file.
                        memory.Close();
                        count += 1;
                    }
                }
                transaction.Complete();
            }
            return View();
        }
Example #19
0
        public static List<Attachment> GetAttachments(params string[] files)
        {
            List<Attachment> attachments = new List<Attachment>();

            if (files != null)
            {
                foreach (string file in files)
                {
                    if (!string.IsNullOrWhiteSpace(file))
                    {
                        using (Attachment attachment = new Attachment(file, MediaTypeNames.Application.Octet))
                        {
                            ContentDisposition disposition = attachment.ContentDisposition;
                            disposition.CreationDate = File.GetCreationTime(file);
                            disposition.ModificationDate = File.GetLastWriteTime(file);
                            disposition.ReadDate = File.GetLastAccessTime(file);

                            disposition.FileName = Path.GetFileName(file);
                            disposition.Size = new FileInfo(file).Length;
                            disposition.DispositionType = DispositionTypeNames.Attachment;

                            attachments.Add(attachment);
                        }
                    }
                }
            }

            return attachments;
        }
        protected void bt_enviar_Click(object sender, EventArgs e)
        {
            
            string Body = System.IO.File.ReadAllText(Server.MapPath("Mails/mail.htm"));
            adjunto = new Attachment("C:adjunto.txt"); //lo adjuntamos
            msg.Attachments.Add(adjunto);

            msg.Body = Body;
            msg.IsBodyHtml = true;
           
            msg.From = new MailAddress("*****@*****.**");
            msg.To.Add("*****@*****.**");
            msg.Subject = "Centro Salud-Información";
            client.Credentials = new NetworkCredential("*****@*****.**", "sistemamaipu");
            client.Host = "smtp.gmail.com";
            client.Port = 25;
            client.EnableSsl = true;
            client.Send(msg);
            //falta mostrar mensaje de mail enviado!!!!!!!!!!!!!!
            //Darle mejor formato al mail
            //Configurar donde se van guardar los adjuntos..
            //habría que ver donde se generan los reportes!

            

        }
Example #21
0
        public EmailProcessor Attach(Attachment attachment)
        {
            if (!Message.Attachments.Contains(attachment))
                Message.Attachments.Add(attachment);

            return this;
        }
 public ArgsHelp AddAccessoriesNoJs(string filePath, string fileName, string fileID)
 {
     ArgsHelp ah = new ArgsHelp();
     try
     {
         GlobalVar.AttachmentID.Clear();
         // Create  the file attachment for this e-mail message.
         Attachment data = new Attachment(filePath, MediaTypeNames.Application.Octet);//(ofd.FileName, MediaTypeNames.Application.Octet);
         // Add time stamp information for the file.
         ContentDisposition disposition = data.ContentDisposition;
         disposition.CreationDate = System.IO.File.GetCreationTime(filePath);// (ofd.FileName);
         disposition.ModificationDate = System.IO.File.GetLastWriteTime(filePath);// (ofd.FileName);
         disposition.ReadDate = System.IO.File.GetLastAccessTime(filePath);// (ofd.FileName);
         // Add the file attachment to this e-mail message.
         if (GlobalVar.AttachmentID.Contains(fileID))
             throw new Exception("已经存在");
         else
         {
             GlobalVar.AttachmentID.Add(fileID);
             GlobalVar.message.Attachments.Add(data);
         }
     }
     catch (Exception e)
     {
         ah.flag = false;
         ah.msg = e.Message;
     }
     return ah;
 }
        private void btnEnviar_Click(object sender, EventArgs e)
        {
            if (!(lblCorreo.Text.Trim() == ""))
            {
                to = lblCorreo.Text;
                sub = txtAsunto.Text;
                body = txtContenido.Text;
                From = txtDe.Text;

                mail = new MailMessage();
                mail.To.Add(new MailAddress(this.to));
                mail.From = new MailAddress(this.From);
                mail.Subject = sub;
                mail.Body = body;
               // mail.passwor = new MailAddress(this.passwor);
                mail.IsBodyHtml = false;

                if (!(txtAsunto.Text.Trim() == ""))
                {
                    data = new Attachment(txtAsunto.Text, MediaTypeNames.Application.Octet);
                    mail.Attachments.Add(data);
                }
                SmtpClient client = new SmtpClient("smtp.live.com", 587);
                using (client)
                {
                   // client.Credentials = new System.Net.NetworkCredential(this.txtDe,txtPassword);
                    client.EnableSsl = true;
                    client.Send(mail);

                }
                MessageBox.Show("enviado");
            }
        }
Example #24
0
    public static void enviarMail(string nomeDe, string passwordDe, string para, string assunto, string texto, string anexo = null)
    {
        //objetos mail
        System.Net.Mail.MailMessage  mensagem    = new System.Net.Mail.MailMessage();
        System.Net.NetworkCredential credenciais = new System.Net.NetworkCredential(nomeDe, passwordDe);
        System.Net.Mail.MailAddress  dequem      = new System.Net.Mail.MailAddress(nomeDe);
        System.Net.Mail.SmtpClient   smtp        = new System.Net.Mail.SmtpClient();

        //mensagem
        mensagem.To.Add(para);
        mensagem.From       = dequem;
        mensagem.Subject    = assunto;
        mensagem.Body       = texto;
        mensagem.IsBodyHtml = true;
        //servidor
        smtp.Host                  = "smtp.gmail.com";
        smtp.Port                  = 587;
        smtp.EnableSsl             = true;
        smtp.DeliveryMethod        = System.Net.Mail.SmtpDeliveryMethod.Network;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials           = credenciais;

        //anexo
        if (anexo != null && anexo != "")
        {
            if (System.IO.File.Exists(anexo) == true)
            {
                System.Net.Mail.Attachment ficheiroAnexo = new System.Net.Mail.Attachment(anexo);
                mensagem.Attachments.Add(ficheiroAnexo);
            }
        }
        //enviar
        smtp.Send(mensagem);
    }
Example #25
0
        public StdResult<NoType> SendMail(string mailTo, string mailSubject, string mailContent, Attachment attachedFile, string ccs)
        {
            try
            {
                MailHelper mh = new MailHelper(MailType.BasicText);
                mh.MailSubject = mailSubject;
                mh.MailType = MailType.BasicText;
                string emailConf = mailTo;

                mh.Recipients = emailConf.Split(',').ToList().ConvertAll(emailAddress => new MailAddress(emailAddress));
                mh.Sender = new MailAddress("*****@*****.**");
                mh.ReplyTo = new MailAddress("*****@*****.**");
                mh.Content = mailContent;
                if(!string.IsNullOrWhiteSpace(ccs))
                    mh.CCs = ccs.Split(',').ToList().ConvertAll(emailAddress => new MailAddress(emailAddress));
                if (attachedFile != null)
                {
                    mh.Attachments = new List<Attachment> { attachedFile };
                }
                LogDelegate(string.Format("Mailer is gonna send a mail to {0}", mailTo));
                //mh.SetContentDirect(text);

                mh.Send();
                return StdResult<NoType>.OkResult;
            }
            catch (Exception e)
            {
                LogDelegate(string.Format("Exception while sending mail to {0}. E = {1} [{2}]", mailTo, e.Message, e.StackTrace));
                return StdResult<NoType>.BadResult(e.Message);
            }
        }
        public Attachment()
        {
            MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(""));
            this.Stream = stream;

            _attachment = new net.Attachment(this.Stream, "");
        }
        public void SendMail(string MailTo, string MailFrom, string attachFiles, string Subject, String Content)
        {
            try
            {
                string from = MailFrom;
                MailAddress mailFrom = new MailAddress(from);
                string to = MailTo;
                MailAddress mailTo = new MailAddress(to);

                using (MailMessage message = new MailMessage(mailFrom, mailTo))
                {
                    message.Priority = MailPriority.Normal;
                    message.Subject = Subject;
                    message.Body = Content;
                    message.Priority = MailPriority.Normal;
                    if (!string.IsNullOrWhiteSpace(attachFiles))
                    {
                        Attachment fileToAttch = new Attachment(attachFiles);
                        message.Attachments.Add(fileToAttch);
                    }

                    SmtpClient client = new SmtpClient();

                    client.Send(message);
                }
            }
            catch (Exception ex)
            {
                //Log Exceptions
            }
        }
Example #28
0
        public virtual MvcMailMessage SBF(SBFEmailViewModel sbf,HttpPostedFileBase file,string subject)
        {
            string receviermail = WebConfigurationManager.AppSettings["ToEmail"];
            ViewData.Model = sbf;
            if (file != null && file.ContentLength > 0)
            {
                var attachment = new Attachment(file.InputStream,sbf.Invoice.SupportingDocuments);
                return Populate(x =>
                {
                    x.ViewName = "sbf";
                    x.To.Add("*****@*****.**");
                    x.CC.Add(receviermail);
                    x.Subject = subject;
                    x.Attachments.Add(attachment);
                });
            }
            else
            {
                return Populate(x =>
                {
                    x.ViewName = "sbf";
                    x.To.Add("*****@*****.**");
                    x.CC.Add(receviermail);
                    x.Subject = subject;

                });
            }
            //return PopulateBody(mailMessage, "SBF");
        }
        /// <summary>
        /// Отправка почтовое сообщение
        /// </summary>
        /// <param name="mailFrom">адрес от</param>
        /// <param name="mailTo">адрес кому</param>
        /// <param name="mailSubject">предмет сообщения (заголовок)</param>
        /// <param name="mailBody">текст сообщения</param>
        /// <param name="mailSmtpServer">почтовый сервер</param>
        /// <param name="FileName">наименование файла</param>
        /// <returns>успех/неудача</returns>
        public static bool SendMail(string mailFrom, string mailTo, string mailSubject, string mailBody, IEnumerable<HttpPostedFileBase> files, bool isHtml = true) {
            bool _mailSended;
            try {
                MailMessage message = new MailMessage(mailFrom, mailTo, mailSubject, mailBody);
                if (files != null) {
                    foreach (HttpPostedFileBase file in files) {
                        Attachment data = new Attachment(file.InputStream, file.ContentType);
                        ContentDisposition disposition = data.ContentDisposition;
                        disposition.CreationDate = System.IO.File.GetCreationTime(file.FileName);
                        disposition.ModificationDate = System.IO.File.GetLastWriteTime(file.FileName);
                        disposition.ReadDate = System.IO.File.GetLastAccessTime(file.FileName);
                        message.Attachments.Add(data);
                    }
                }
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                message.IsBodyHtml = isHtml;

                SmtpClient client = new SmtpClient("localhost");
                client.Credentials = CredentialCache.DefaultNetworkCredentials;
                client.Send(message);
                _mailSended = true;
            }
            catch (Exception ex) {
                _mailSended = false;
                string inner = ex.InnerException != null ? inner = ex.InnerException.Message : "нет";
            }
            return _mailSended;
        }
Example #30
0
        public static void SendEmail(EmailSenderData emailData)
        {
            MailMessage mail = new MailMessage();
            SmtpClient smtpServer = new SmtpClient(emailData.SmtpClient);
            smtpServer.Port = 25;
            mail.From = new MailAddress(emailData.FromEmail);

            foreach (string currentEmail in emailData.Emails)
            {
                mail.To.Add(currentEmail);
            }
            mail.Subject = emailData.Subject;
            mail.IsBodyHtml = true;
            mail.Body = emailData.EmailBody;

            if (emailData.AttachmentPath != null)
            {                
                foreach (string currentPath in emailData.AttachmentPath)
                {
                    Attachment  attachment = new Attachment(currentPath);
                    mail.Attachments.Add(attachment);                    
                }               
                smtpServer.Send(mail);
                DisposeAllAttachments(mail);
            }
            else
            {
                smtpServer.Send(mail);
            }

            mail.Dispose();
            smtpServer.Dispose();
        }
 public void Build_MessageHasAttachments_AddsAttachmentParts()
 {
     var attachment = new Attachment(new MemoryStream(), "Test Attachment");
     var message = BuildMessage(x => x.Attachments.Add(attachment));
     var result = FormPartsBuilder.Build(message);
     result.AssertContains(attachment);
 }
Example #32
0
        public static bool SendMail(string fromEmail, List<string> emailTo, List<string> emailCC, string subjectLine,
            string bodyText, bool isHTML, List<string> attachments)
        {
            HttpContext context = HttpContext.Current;
            EMailSettings mailSettings = EMailSettings.GetEMailSettings();

            if (String.IsNullOrEmpty(fromEmail)) {
                fromEmail = mailSettings.ReturnAddress;
            }

            if (emailTo != null && emailTo.Any()) {
                MailMessage message = new MailMessage {
                    From = new MailAddress(fromEmail),
                    Subject = subjectLine,
                    Body = bodyText,
                    IsBodyHtml = isHTML
                };

                message.Headers.Add("X-Computer", Environment.MachineName);
                message.Headers.Add("X-Originating-IP", context.Request.ServerVariables["REMOTE_ADDR"].ToString());
                message.Headers.Add("X-Application", "Carrotware Web " + CurrentDLLVersion);
                message.Headers.Add("User-Agent", "Carrotware Web " + CurrentDLLVersion);
                message.Headers.Add("Message-ID", "<" + Guid.NewGuid().ToString().ToLowerInvariant() + "@" + mailSettings.MailDomainName + ">");

                foreach (var t in emailTo) {
                    message.To.Add(new MailAddress(t));
                }

                if (emailCC != null) {
                    foreach (var t in emailCC) {
                        message.CC.Add(new MailAddress(t));
                    }
                }

                if (attachments != null) {
                    foreach (var f in attachments) {
                        Attachment a = new Attachment(f, MediaTypeNames.Application.Octet);
                        ContentDisposition disp = a.ContentDisposition;
                        disp.CreationDate = System.IO.File.GetCreationTime(f);
                        disp.ModificationDate = System.IO.File.GetLastWriteTime(f);
                        disp.ReadDate = System.IO.File.GetLastAccessTime(f);
                        message.Attachments.Add(a);
                    }
                }

                SmtpClient client = new SmtpClient();
                if (mailSettings.DeliveryMethod == SmtpDeliveryMethod.Network
                        && !String.IsNullOrEmpty(mailSettings.MailUserName)
                        && !String.IsNullOrEmpty(mailSettings.MailPassword)) {
                    client.Host = mailSettings.MailDomainName;
                    client.Credentials = new NetworkCredential(mailSettings.MailUserName, mailSettings.MailPassword);
                } else {
                    client.Credentials = new NetworkCredential();
                }

                client.Send(message);
            }

            return true;
        }
 /// <summary>
 /// Constructor for Custom Smtp Client.
 /// </summary>
 /// <param name="usr">Username</param>
 /// <param name="pass">Password</param>
 /// <param name="mailTo">Email address of the recipient</param>
 /// <param name="mailFrom">Who the mail is coming from</param>
 /// <param name="subject">The Subject of the email</param>
 /// <param name="attachments">Attachemts added to email</param>
 public CSmtpClient(string usr, string pass, string mailTo, string mailFrom, string subject, string message, Attachment[] attachments)
     : this(usr, pass, mailTo, mailFrom, subject, message)
 {
     foreach (Attachment att in attachments)
     objMail.Attachments.Add(att);
       this.usr = usr;
 }
Example #34
0
    public void SendPdfViaEmail()
    {
        try
        {
            PdfDocument doc = GetPdf();
            using (MemoryStream memoryStream = new MemoryStream(doc.Save()))
            {
                System.Net.Mime.ContentType ct         = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
                System.Net.Mail.Attachment  attachment = new System.Net.Mail.Attachment(memoryStream, ct);
                attachment.ContentDisposition.FileName = fileName;

                Mailer.SendEmail("Invoice", "Please find invoice attached", user.Email, null, null, attachments: new System.Net.Mail.Attachment[1] {
                    attachment
                });
            }
        }
        catch (Exception ex)
        {
            ErrorLogger.Log(ex);
        }
    }
Example #35
0
        private void SendEmail(string orderId)
        {
            string arquivo          = $"{diretorioLocal}\\{orderId}{extensao}";
            string emailTo          = config.GetSection("Parametros:Email:EmailTo").Value;
            string emailCredentials = config.GetSection("Parametros:Email:EmailFrom").Value;
            string senhaCredentials = config.GetSection("Parametros:Email:Senha").Value;
            string smtpClient       = config.GetSection("Parametros:Email:SmtpClient").Value;
            int    smtpPort         = int.Parse(config.GetSection("Parametros:Email:SmtpPort").Value);

            MailMessage mail       = new MailMessage();
            SmtpClient  SmtpServer = new SmtpClient(smtpClient);

            mail.From = new MailAddress(emailCredentials);
            mail.To.Add(emailTo);
            mail.Subject = $"pedido: {orderId}";
            mail.Body    = $"Arquivo {extensao} com o pedido: {orderId}";
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(arquivo);
            mail.Attachments.Add(attachment);
            SmtpServer.Port        = smtpPort;
            SmtpServer.Credentials = new System.Net.NetworkCredential(emailCredentials, senhaCredentials);
            SmtpServer.EnableSsl   = true;
            SmtpServer.Send(mail);
            Console.WriteLine($"Email enviado para {emailTo}");
        }
Example #36
0
        public static void Send()
        {
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("from");
                mail.To.Add("to");


                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(@"C:\Users\user\xz.txt");
                mail.Attachments.Add(attachment);

                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("from", "password");
                SmtpServer.EnableSsl   = true;

                SmtpServer.Send(mail);
            }
            catch (Exception ex)
            {
            }
        }
Example #37
0
        /// <summary>
        /// </summary>
        /// <param name="mailMessage"></param>
        /// <param name="message"></param>
        private void AddAttachments(Nm.MailMessage mailMessage, IMailMessage message)
        {
            if (mailMessage == null)
            {
                throw new ArgumentNullException("mailMessage");
            }
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            // attach...
            foreach (MailAttachment attachment in message.Attachments)
            {
                Nm.Attachment mailAttachment = this.ToNmMailAttachment(attachment);
                if (mailAttachment == null)
                {
                    throw new InvalidOperationException("mailAttachment is null.");
                }

                // add...
                mailMessage.Attachments.Add(mailAttachment);
            }
        }
Example #38
0
        public void senmail2(string destinatarios, string mensaje, string Asunto, string archivo, string para)
        {
            try
            {
                // string[] cr = destinatarios.Split(";");
                Application oApp1 = new Application();
                MailItem    ema   = (MailItem)oApp1.CreateItem(OlItemType.olMailItem);
                //ema. = new MailAddress(para);
                ema.To      = para;
                ema.Subject = Asunto;
                ema.Body    = mensaje;

                ema.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh;
                System.Net.Mail.Attachment archin = new System.Net.Mail.Attachment(archivo);
                ema.Attachments.Add(archivo, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                ema.Save();
                //item.Display(true);
                ema.Send();
            }
            catch (System.Exception ex)
            {
                throw (ex);
            }
        }
Example #39
0
        //Metodo para mandar emails a partir de un correo
        private void mandar_mail(String pdfTicket)
        {
            try
            {
                string email    = "*****@*****.**";         //Guardamos el email en un string
                string password = txtPasswordEmpresa.Text;               //Obtenemos la contraseña de un TextBox

                var loginInfo  = new NetworkCredential(email, password); //Creamos unas nueva credencial con la informacion del email
                var msg        = new MailMessage();                      //Creamos un nuevo mensaje
                var smtpClient = new SmtpClient("smtp.gmail.com", 25);   //Creamos un nuevo cliente con los datos del servicio a usar

                //Pasamos configuraciones del mensaje
                msg.From = new MailAddress(email);
                msg.To.Add(new MailAddress(txtCliente.Text));
                msg.Subject = "Factura Farmacia ";
                msg.Body    = "Ticket De compra";
                //Adjuntamos un fichero
                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(pdfTicket);
                msg.Attachments.Add(attachment);



                msg.IsBodyHtml = true;

                //Cargamos en el smtpClient las credenciales y enviamos el mensaje
                smtpClient.EnableSsl             = true;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials           = loginInfo;

                smtpClient.Send(msg);
                smtpClient.Dispose();
            }catch (Exception ex)
            {
            }
        }
Example #40
0
        private static void SendTo(string emailFrom, string emailTo, string emailSubject, string smtpPort, string smtpServer, string emailPwd, string sFile, string emailBody)
        {
            SmtpClient  SmtpServer = new SmtpClient(smtpServer);
            MailMessage mail       = new MailMessage();

            mail.From = new MailAddress(emailFrom);
            foreach (var recipient in emailTo.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                mail.To.Add(recipient);
            }

            mail.Subject = emailSubject;
            mail.Body    = emailBody;

            System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(sFile);
            mail.Attachments.Add(attachment);

            SmtpServer.Port        = System.Convert.ToInt16(smtpPort);
            SmtpServer.Credentials = new System.Net.NetworkCredential(emailFrom, emailPwd);
            SmtpServer.EnableSsl   = true;
            SmtpServer.Timeout     = 7200000;
            SmtpServer.Send(mail);
        }
Example #41
0
        public static Attachment[] GetAttachments(string[] files)
        {
            if (files == null)
            {
                return(null);
            }
            var attachments = new List <Attachment>();

            for (int i = 0; i < files.Count(); i++)
            {
                string file = files[i];
                if (string.IsNullOrEmpty(file))
                {
                    continue;
                }
                if (System.IO.File.Exists(file))
                {
                    // Specify as "application/octet-stream" so attachment will never will be embedded in body of email.
                    var att = new System.Net.Mail.Attachment(file, "application/octet-stream");
                    attachments.Add(att);
                }
            }
            return(attachments.ToArray());
        }
Example #42
0
        //public string TestEmailSettings(DepartmentCallEmail emailSettings)
        //{
        //	return _callEmailProvider.TestEmailSettings(emailSettings);
        //}

        public void SendReportDeliveryEmail(EmailNotification email)
        {
            using (var mail = new MailMessage())
            {
                mail.To.Add(email.To);
                mail.Subject = email.Subject;
                mail.From    = new MailAddress("*****@*****.**", "Resgrid Report Delivery");

                mail.Body       = string.Format("Your scheduled Resgrid report is attached.");
                mail.IsBodyHtml = false;

                var ms = new MemoryStream(email.AttachmentData);
                var a  = new System.Net.Mail.Attachment(ms, email.AttachmentName);
                mail.Attachments.Add(a);

                //_smtpClient.Send(mail);

                try
                {
                    _emailSender.SendEmail(mail);
                }
                catch (SmtpException sex) { }
            }
        }
Example #43
0
        private static void SendMail(string FullPath, string FileName)
        {
            int    SMTPPort      = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);
            string SMTPHost      = ConfigurationManager.AppSettings["SMTPHost"];
            string SMTPTo        = ConfigurationManager.AppSettings["SMTPTo"];
            string SMTPFrom      = ConfigurationManager.AppSettings["SMTPFrom"];
            string SMTPSubj      = ConfigurationManager.AppSettings["SMTPSubj"];
            string SMTPBody      = ConfigurationManager.AppSettings["SMTPBody"];
            bool   SMTPUserCreds = Convert.ToBoolean(ConfigurationManager.AppSettings["SMTPUserCreds"]);
            string SMTPUser      = ConfigurationManager.AppSettings["SMTPUser"];
            string SMTPPass      = ConfigurationManager.AppSettings["SMTPPass"];


            System.Net.Mail.Attachment attachment;

            SmtpClient client = new SmtpClient();

            client.Port                  = SMTPPort;
            client.Host                  = SMTPHost;
            client.EnableSsl             = false;
            client.Timeout               = 40000;
            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = true;

            client.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPass);

            MailMessage mm = new MailMessage(SMTPFrom, SMTPTo, SMTPSubj, SMTPBody);

            attachment = new System.Net.Mail.Attachment(FullPath);
            mm.Attachments.Add(attachment);
            mm.BodyEncoding = UTF8Encoding.UTF8;
            mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            client.Send(mm);
            attachment.Dispose();
        }
        private void sendEmail()
        {
            var user = new EverythingFootballDemo.DAL.User();

            user = (EverythingFootballDemo.DAL.User)Session["userInfo"];
            string     strFrom = ConfigurationManager.AppSettings["SenderEmail"].ToString();
            var        mailMsg = new MailMessage(strFrom, user.EmailID);
            Attachment attachment;

            attachment = new System.Net.Mail.Attachment(@"D:\Images\Ticket.pdf");
            mailMsg.Attachments.Add(attachment);
            mailMsg.Body    = "Congratulations. Your ticket has been generated succesfully";
            mailMsg.Subject = "Ticket Booking Confirmation - The Offside Club";

            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);

            smtp.Credentials = new System.Net.NetworkCredential()
            {
                UserName = ConfigurationManager.AppSettings["UserName"].ToString(),
                Password = ConfigurationManager.AppSettings["Password"].ToString()
            };
            smtp.EnableSsl = true;
            smtp.Send(mailMsg);
        }
Example #45
0
        private void sendEmail(string emailto, string name)
        {
            string      emailFromAddress = "*****@*****.**"; //Sender Email Address
            string      password         = "******";                //Sender Password
            string      emailToAddress   = emailto;                    //Receiver Email Address
            string      subject          = "Osmanabad Covid Care Patient Reports";
            string      body             = "Dear " + name + ",\n\nKindly check the attachment of patients Reports here !!!\n\n\nThanks & Regards,\nApp Development Team,\nLeadSoft IT Solutions,\n7028816463.";
            MailMessage message          = new MailMessage();
            SmtpClient  smtp;

            System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(filename);
            message.Attachments.Add(attachment);
            message.Subject = subject;
            message.Body    = body;
            message.To.Add(new MailAddress(emailto));
            message.From     = new MailAddress(emailFromAddress, "LeadSoft IT Solutions");
            smtp             = new SmtpClient("smtp.gmail.com");
            smtp.Port        = 25;
            smtp.EnableSsl   = true;
            smtp.Credentials = new NetworkCredential(emailFromAddress, password);
            smtp.SendAsync(message, message.Subject);
            smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
        }
Example #46
0
        static void sendemail(Client cl)
        {
            SmtpClient smtp = new SmtpClient
            {
                Host                  = "smtp.gmail.com",
                Port                  = 587,
                EnableSsl             = true,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential("*****@*****.**", "j00natan")
            };

            System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress("*****@*****.**"), new System.Net.Mail.MailAddress((cl.Email)))
            {
                Subject = "luo bordari",
                Body    = "//" + cl.LName + "/" + cl.FName + "/" + cl.FD + "/" + cl.FN
            };

            string        path = "../../docs";
            DirectoryInfo d    = new DirectoryInfo(path);

            foreach (var file in d.GetFiles("*.pdf"))
            {
                try
                {
                    System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(file.FullName);
                    m.Attachments.Add(attachment);
                }
                catch (Exception e) { Console.WriteLine(e.Message); }
            }

            smtp.Send(m);
            smtp.Dispose();
            m.Dispose();
            d = null;
        }
Example #47
0
        //public bool EnviarCorreo(string idCanalContenido, string idContenido, Dictionary<string, string> comodinesNotificacion, string idCanalNotificaciones, string idContenidoNotificaciones, string rutaFrondEnd = "")
        //{
        //    bool result = false;
        //    string destino = "";
        //    try
        //    {
        //        HelperEnviarCorreo.CrearLog("EnviarCorreoComodin - Inicio :");
        //        //List<string> comodines = new List<string>();
        //        List<string> valores = new List<string>();

        //        List<string> comodines = new List<string>();

        //        (new ManejadorLog()).RegistrarEvento("dentro de mailerEnviarCorreo");

        //        //Obtener la plantilla para el envio de correo
        //        ScriptorChannel canalNotificaciones = Common.ScriptorClient.GetChannel(new Guid(idCanalNotificaciones));
        //        ScriptorContent contenidoNotificaciones = canalNotificaciones.GetContent(new Guid(idContenidoNotificaciones));
        //        //ScriptorContent contenidoNotificaciones = canalNotificaciones.Contents.Find(x => x.Id.ToString().ToUpper() == idContenidoNotificaciones.ToUpper());

        //        (new ManejadorLog()).RegistrarEvento("despues de canalNotificaciones");


        //        HelperEnviarCorreo.CrearLog("Bien 1");
        //        //var d = contenidoNotificaciones.Parts.A[0].Parts.A;
        //        var archivos = (ScriptorContentInsert)contenidoNotificaciones.Parts.ArchivosAdjuntos;

        //        HelperEnviarCorreo.CrearLog("Bien 2");
        //        CorreoBE correo = new CorreoBE();

        //        if (contenidoNotificaciones.Parts.CorreoPara != "" && contenidoNotificaciones.Parts.CorreoPara != null)
        //        {
        //            correo.Para.Add(contenidoNotificaciones.Parts.CorreoPara);
        //        }

        //        if (comodinesNotificacion != null && comodinesNotificacion.ContainsKey("_para_"))
        //        {
        //            correo.Para.Clear();
        //            destino = comodinesNotificacion["_para_"];
        //            correo.Para.Add(destino);
        //            comodinesNotificacion.Remove("_para_");
        //        }
        //        HelperEnviarCorreo.CrearLog("Bien 3");


        //        if (idCanalContenido != string.Empty && idContenido != string.Empty)
        //        {
        //            //Obtener el contenido para reemplazar los valores en el cuerpo del correo
        //            ScriptorChannel canalContenido = Common.ScriptorClient.GetChannel(new Guid(idCanalContenido));
        //            ScriptorContent contenido = canalContenido.GetContent(new Guid(idContenido));

        //            //ScriptorContent contenido = canalContenido.Contents.Find(x => x.Id.ToString().ToUpper() == idContenido.ToUpper());
        //            HelperEnviarCorreo.CrearLog(idContenido.ToUpper());

        //            if (correo.Para.Count == 0)
        //            {
        //                HelperEnviarCorreo.CrearLog("correo1");

        //                if (contenido.Parts.NombreCompleto != "" && contenido.Parts.NombreCompleto != null)
        //                {
        //                    HelperEnviarCorreo.CrearLog("correo2");
        //                    correo.Para.Add(contenido.Parts.NombreCompleto);
        //                    HelperEnviarCorreo.CrearLog("correo3");
        //                }
        //            }

        //            foreach (var llave in contenido.Parts.Values)
        //            {
        //                string valor = "";

        //                if (llave.GetType().ToString() == "Viatecla.Factory.Scriptor.ScriptorDropdownListValue")
        //                {
        //                    valor = llave.Title;
        //                }
        //                else if (llave.GetType().ToString() == "Viatecla.Factory.Scriptor.ScriptorContentInsert")
        //                {

        //                }
        //                else
        //                {
        //                    valor = llave;
        //                }

        //                valores.Add(valor);
        //            }

        //            comodines = new List<string>(contenido.Parts.Keys);
        //        }
        //        else
        //        {
        //            comodines = comodinesNotificacion.Keys.ToList<string>();
        //            valores = comodinesNotificacion.Values.ToList<string>();
        //        }

        //        HelperEnviarCorreo.CrearLog("Bien 4");
        //        if (contenidoNotificaciones.Parts.CorreoCCO != "" && contenidoNotificaciones.Parts.CorreoCCO != null)
        //        {
        //            correo.ConCopiaOculta.Add(contenidoNotificaciones.Parts.CorreoCCO);
        //        }

        //        HelperEnviarCorreo.CrearLog("Bien 5");
        //        String from = contenidoNotificaciones.Parts.CorreoDe;

        //        correo.Asunto = contenidoNotificaciones.Parts.Asunto;
        //        correo.CuerpoMensaje = contenidoNotificaciones.Parts.CorreoBody.ToString();

        //        HelperEnviarCorreo.CrearLog("Bien 6");
        //        //correo.CuerpoMensaje = ReemplazarComodines(correo.CuerpoMensaje, this.GetComodines(comodines), valores, rutaFrondEnd);

        //        correo.ArchivosAdjuntos = this.GetArchivosAdjuntos(archivos, rutaFrondEnd);

        //        HelperEnviarCorreo helperEnviarCorreo = new HelperEnviarCorreo(from);
        //        helperEnviarCorreo.EnviarCorreoLocal(correo);

        //        HelperEnviarCorreo.CrearLog("EnviarCorreoComodin - Fin:");

        //        result = true;

        //    }
        //    catch (Exception ex)
        //    {
        //        HelperEnviarCorreo.CrearLog("EnviarCorreoComodin - Error:" + ex.Message);
        //        HelperEnviarCorreo.CrearLog("EnviarCorreoComodin - Error:" + ex.InnerException);
        //        HelperEnviarCorreo.CrearLog("EnviarCorreoComodin - Error:" + ex.StackTrace);
        //        result = false;
        //    }

        //    return result;
        //}

        //public List<ArchivoAdjunto> GetArchivosAdjuntos(ScriptorContentInsert contentInsert, string pathFrontEnd)
        //{
        //    List<ArchivoAdjunto> archivoAdjuntoList = new List<ArchivoAdjunto>();

        //    foreach (ScriptorContent content in contentInsert)
        //    {
        //        ArchivoAdjunto archivoAdjunto = new ArchivoAdjunto();
        //        archivoAdjunto.NombreArchivo = content.Parts.Titulo;
        //        archivoAdjunto.RutaArchivoWeb = string.Format("{0}{1}", pathFrontEnd, content.Parts.ArchivoAdjunto);
        //        archivoAdjunto.RutaArchivoWeb = archivoAdjunto.GetRutaArchivoWebFront();
        //        archivoAdjuntoList.Add(archivoAdjunto);
        //    }

        //    return archivoAdjuntoList;
        //}

        private void EnviarCorreo_Aux(CorreoBE correo,
                                      Boolean isbodyHtml,
                                      System.Net.Mail.MailPriority prioridad)
        {
            System.Net.Mail.MailMessage Mail = new System.Net.Mail.MailMessage();

            isbodyHtml = true;
            prioridad  = System.Net.Mail.MailPriority.High;

            List <LinkedResource> lstLinked = new List <LinkedResource>();

            //'----------------------------------------------------------------------------------
            if (correo.Para != null)
            {
                foreach (String reg in correo.Para)
                {
                    Mail.To.Add(reg);
                }
            }
            if (correo.ConCopia != null)
            {
                foreach (String reg in correo.ConCopia)
                {
                    Mail.CC.Add(reg);
                }
            }
            if (correo.ConCopiaOculta != null)
            {
                foreach (String reg in correo.ConCopiaOculta)
                {
                    Mail.Bcc.Add(reg);
                }
            }
            if (correo.ArchivosAdjuntos != null)
            {
                foreach (ArchivoAdjunto reg in correo.ArchivosAdjuntos)
                {
                    if (String.IsNullOrEmpty(reg.RutaArchivoDisco))
                    {
                        if (!String.IsNullOrEmpty(reg.RutaArchivoWeb))
                        {
                            System.Net.Mail.Attachment archivo = null;
                            switch (System.Configuration.ConfigurationManager.AppSettings["TipoCorreoAdjunto"])
                            {
                            case "1":    //adjunto
                                reg.RutaArchivoDisco = HelperEnviarCorreo.GuardarImagenDeUrl(reg.RutaArchivoWeb, reg.NombreArchivo);
                                //adjunto
                                archivo = new System.Net.Mail.Attachment(reg.RutaArchivoDisco);
                                Mail.Attachments.Add(archivo);
                                break;

                            case "2":    //base64

                                if (reg.NombreArchivo.ToUpper().Contains(".PNG") ||
                                    reg.NombreArchivo.ToUpper().Contains(".JPEG") ||
                                    reg.NombreArchivo.ToUpper().Contains(".GIF") ||
                                    reg.NombreArchivo.ToUpper().Contains(".JPG"))
                                {
                                    /*
                                     * string imagen64bits = "";
                                     * reg.RutaArchivoDisco = HelperEnviarCorreo.GuardarImagenDeUrl(reg.RutaArchivoWeb, reg.NombreArchivo, out imagen64bits);
                                     * reg.Imagen64bits = imagen64bits;
                                     *
                                     * correo.CuerpoMensaje = correo.CuerpoMensaje.Replace("cid:" + reg.NombreArchivo, "data:image/jpeg;base64," + reg.Imagen64bits);
                                     */
                                    reg.RutaArchivoDisco = HelperEnviarCorreo.GuardarImagenDeUrl(reg.RutaArchivoWeb, reg.NombreArchivo);
                                    LinkedResource sampleImage = new LinkedResource(reg.RutaArchivoDisco,
                                                                                    MediaTypeNames.Image.Jpeg);
                                    sampleImage.ContentId = reg.NombreArchivo;
                                    lstLinked.Add(sampleImage);
                                }
                                else
                                {
                                    reg.RutaArchivoDisco = HelperEnviarCorreo.GuardarImagenDeUrl(reg.RutaArchivoWeb, reg.NombreArchivo);
                                    //adjunto
                                    archivo = new System.Net.Mail.Attachment(reg.RutaArchivoDisco);
                                    Mail.Attachments.Add(archivo);
                                }
                                break;

                            case "3":    //url
                                string   urlDominioWebFrontEnd = System.Configuration.ConfigurationManager.AppSettings["UrlDominioWebFrontEnd"];
                                string   urlTmp       = reg.GetRutaArchivoWebFront();
                                string   urlTmpSufijo = "";
                                string[] listatmp     = urlTmp.Split('/');
                                for (int i = 0; i < listatmp.Length; i++)
                                {
                                    if (i >= 3)
                                    {
                                        urlTmpSufijo = urlTmpSufijo + '/' + listatmp[i];
                                    }
                                }
                                urlTmp = urlDominioWebFrontEnd + urlTmpSufijo;
                                correo.CuerpoMensaje = correo.CuerpoMensaje.Replace("cid:" + reg.NombreArchivo, urlTmp);
                                break;
                            }
                        }
                    }
                }
            }



            Mail.From = new System.Net.Mail.MailAddress(this.From);

            Mail.Subject    = correo.Asunto;
            Mail.IsBodyHtml = isbodyHtml;
            Mail.Body       = correo.CuerpoMensaje;
            switch (System.Configuration.ConfigurationManager.AppSettings["TipoCorreoAdjunto"])
            {
            case "2":    //adjunto
            {
                /*ContentType mimeType = new System.Net.Mime.ContentType("text/html");
                 * AlternateView alternate = AlternateView.CreateAlternateViewFromString(correo.CuerpoMensaje, mimeType);
                 * Mail.AlternateViews.Add(alternate);*/
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(correo.CuerpoMensaje, null, MediaTypeNames.Text.Html);
                foreach (var item in lstLinked)
                {
                    htmlView.LinkedResources.Add(item);
                }
                Mail.AlternateViews.Add(htmlView);
            }
            break;
            }

            //'----------------------------------------------------------------------------------
            SmtpClient cliente = new SmtpClient();

            cliente.Host = "" + System.Configuration.ConfigurationManager.AppSettings["Host"];
            if (Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Port"]) != "")
            {
                cliente.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]);
            }
            cliente.EnableSsl             = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["EnableSsl"]);
            cliente.UseDefaultCredentials = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseDefaultCredentials"]);
            if (cliente.UseDefaultCredentials == false)
            {
                cliente.Credentials = new NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["CredentialsUser"], "" + System.Configuration.ConfigurationManager.AppSettings["CredentialsClave"]);
            }

            //'----------------------------------------------------------------------------------
            try
            {
                cliente.Send(Mail);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Example #48
0
        private void button1_Click(object sender, EventArgs e)
        {
            pBar.Value = 0;

            MailMessage mail;
            SmtpClient  SmtpServer;

            SmtpServer             = new SmtpClient(textBox3.Text);
            SmtpServer.Port        = int.Parse(textBox5.Text);
            SmtpServer.Credentials = new System.Net.NetworkCredential(textBox7.Text, textBox6.Text);
            SmtpServer.EnableSsl   = true;
            mail      = new MailMessage();
            mail.From = new MailAddress(textBox7.Text, senderName.Text);


            mail.Subject = textBox2.Text;
            mail.Body    = textBox4.Text;


            if (textBox8.Text != String.Empty)
            {
                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(textBox8.Text);
                mail.Attachments.Add(attachment);
            }

            if (html)
            {
                mail.IsBodyHtml = true;
                MessageBox.Show("html true");
            }

            try
            {
                int count = 0, total = 0;
                pBar.Minimum = 0;



                if (multiple)
                {
                    groupBox6.Visible = true;
                    groupBox5.Visible = false;

                    List <string> addyList = new List <string>();
                    foreach (string line in File.ReadLines(textBox9.Text))
                    {
                        addyList.Add(line);
                        total++;
                    }
                    pBar.Maximum = total;
                    label14.Text = total.ToString();

                    foreach (string address in addyList)
                    {
                        mail.To.Clear();
                        MailAddress to = new MailAddress(address);
                        mail.To.Add(to);
                        try
                        {
                            SmtpServer.Send(mail);
                            richTextBox1.AppendText("\r\n" + to + "            OK!");
                            richTextBox1.ScrollToCaret();
                            pBar.Value = count + 1;
                            count++;
                            label12.Text = count.ToString();
                        }
                        catch
                        {
                            richTextBox1.AppendText("\r\n" + to + "            FAILED!");
                            richTextBox1.ScrollToCaret();
                            count++;
                            label12.Text = count.ToString();
                        }
                    }
                    MessageBox.Show("COMPLETE");
                }
                else
                {
                    groupBox6.Visible = true;
                    groupBox5.Visible = false;
                    count             = 0;
                    pBar.Maximum      = 1;
                    label14.Text      = "1";
                    MailAddress to = new MailAddress(textBox1.Text);
                    mail.To.Add(to);


                    try
                    {
                        SmtpServer.Send(mail);
                        richTextBox1.AppendText("\r\n" + to + "            OK!");
                        richTextBox1.ScrollToCaret();
                        pBar.Value   = count + 1;
                        label12.Text = "1";
                    }
                    catch
                    {
                        richTextBox1.AppendText("\r\n" + to + "            FAILED!");
                        richTextBox1.ScrollToCaret();
                        label12.Text = "1";
                    }
                    MessageBox.Show("COMPLETE");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public bool ResumeUpload(FormCollection fc, HttpPostedFileBase file)
        {
            string name  = string.Empty;
            string email = string.Empty;
            string path  = "";

            if (fc[0].ToString() != null && fc[1].ToString() != null)
            {
                name  = fc["name"].ToString();
                email = fc["email"].ToString();
            }

            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    path = Path.Combine(Server.MapPath("~/PluginScripts/Images/resume"),
                                        Path.GetFileName(file.FileName));
                    file.SaveAs(path);

                    TempData["Message"] = "File uploaded successfully";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                    return(false);
                }
            }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }



            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add("*****@*****.**");
                mail.Subject = "Resume: " + name + "-Email: " + email;
                mail.Body    = "mail with attachment";

                if (path != "")
                {
                    System.Net.Mail.Attachment attachment;
                    attachment = new System.Net.Mail.Attachment(path);
                    mail.Attachments.Add(attachment);
                }
                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "wasi.rehman9027413884");
                SmtpServer.EnableSsl   = true;

                SmtpServer.Send(mail);
            }
            catch (Exception e)
            {
                return(false);
            }


            return(true);
        }
Example #50
0
        protected override ActionResult DoActionProcessing(Job job)
        {
            var smtpAccount = job.Accounts.GetSmtpAccount(job.Profile);

            if (string.IsNullOrEmpty(job.Passwords.SmtpPassword))
            {
                Logger.Error("SendMailOverSmtp canceled. Action launched without Password.");
                return(new ActionResult(ErrorCode.Smtp_NoPasswordSpecified));
            }

            MailMessage mail;

            try
            {
                mail = new MailMessage(smtpAccount.Address, job.Profile.EmailSmtpSettings.Recipients);
            }
            catch (Exception e) when(e is FormatException || e is ArgumentException)
            {
                Logger.Error($"\'{job.Profile.EmailSmtpSettings.Recipients}\' is no valid SMTP e-mail recipient: " + e.Message);
                return(new ActionResult(ErrorCode.Smtp_InvalidRecipients));
            }

            // these blocks have to be seperated, because we want to log the offending recipients
            // (AddRecipients does this already, but can't be reused for the constructor)
            try
            {
                AddRecipients(mail, RecipientType.Cc, job.Profile.EmailSmtpSettings.RecipientsCc);
                AddRecipients(mail, RecipientType.Bcc, job.Profile.EmailSmtpSettings.RecipientsBcc);
            }
            catch
            {
                return(new ActionResult(ErrorCode.Smtp_InvalidRecipients));
            }

            mail.Subject    = job.TokenReplacer.ReplaceTokens(job.Profile.EmailSmtpSettings.Subject);
            mail.IsBodyHtml = job.Profile.EmailSmtpSettings.Html;
            mail.Body       = job.TokenReplacer.ReplaceTokens(job.Profile.EmailSmtpSettings.Content);

            if (job.Profile.EmailSmtpSettings.AddSignature)
            {
                var mailSignature = _mailSignatureHelper.ComposeMailSignature();

                // if html option is checked replace newLine with <br />
                if (job.Profile.EmailSmtpSettings.Html)
                {
                    mailSignature = mailSignature.Replace(Environment.NewLine, "<br>");
                }

                mail.Body += mailSignature;
            }

            Logger.Debug("Created new Mail"
                         + "\r\nFrom: " + mail.From
                         + "\r\nTo: " + mail.To
                         + "\r\nSubject: " + mail.Subject
                         + "\r\nContent: " + mail.Body
                         );

            if (!SkipFileAttachments(job))
            {
                var i = 1;
                foreach (var file in job.OutputFiles)
                {
                    var attach = new Attachment(file);
                    //attach.NameEncoding = System.Text.Encoding.ASCII;
                    mail.Attachments.Add(attach);
                    Logger.Debug("Attachement " + i + "/" + job.OutputFiles.Count + ":" + file);
                    i++;
                }
            }

            var smtp = new SmtpClient(smtpAccount.Server, smtpAccount.Port);

            smtp.EnableSsl = smtpAccount.Ssl;

            Logger.Debug("Created new SmtpClient:"
                         + "\r\nHost: " + smtp.Host
                         + "\r\nPort: " + smtp.Port
                         );

            return(SendEmail(job, smtp, mail));
        }
Example #51
0
        public static bool Send(string subject, string message, string ReceiverEmail, IConfiguration _config, string attachementfilepath = null, string MailsToCopy = "")
        {
            bool flag = false;

            string sender         = _config.GetSection("UserName").ToString();
            string senderpassword = _config.GetSection("sPassword").ToString();
            string receiver       = ReceiverEmail;
            //  WebConfigurationManager.AppSettings("ReceiverEmail").ToString()
            int    mailportnumber = int.Parse(_config.GetSection("Port").ToString());
            string mailserver     = _config.GetSection("Host").ToString();

            //   Dim mailreceivers As String()
            // string deliverystatus = "0";

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

            System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType("text/html");
            string body = System.Web.HttpUtility.HtmlDecode(message);

            mailmsg.SubjectEncoding = Encoding.UTF8;
            mailmsg.From            = new System.Net.Mail.MailAddress(sender, "Edufund", Encoding.UTF8);
            string[] receivers = receiver.Split(',');
            for (int i = 0; i <= receiver.Split(',').Length - 1; i++)
            {
                if (receivers[i].Contains("@"))
                {
                    mailmsg.To.Add(new System.Net.Mail.MailAddress(receivers[i]));
                }
            }
            String[] mailtocopy = MailsToCopy.Split(',');
            if ((MailsToCopy != null))
            {
                if (!MailsToCopy.Contains("nbsp"))
                {
                    for (int i = 0; i <= MailsToCopy.Split(',').Length - 1; i++)
                    {
                        if (mailtocopy[i].Contains("@"))
                        {
                            mailmsg.CC.Add(new System.Net.Mail.MailAddress(mailtocopy[i]));
                        }
                    }
                }
            }
            //Try
            if ((attachementfilepath != null))
            {
                MemoryStream strm = new MemoryStream(File.ReadAllBytes(attachementfilepath));
                System.Net.Mime.ContentType contype = new System.Net.Mime.ContentType();
                contype.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;
                FileInfo fil = new FileInfo(attachementfilepath);
                contype.Name = fil.Name;
                System.Net.Mail.Attachment atc = new System.Net.Mail.Attachment(strm, contype);
                mailmsg.Attachments.Add(atc);
            }

            try
            {
                System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(mailserver, mailportnumber);
                client.EnableSsl             = true;
                client.UseDefaultCredentials = false;
                client.Credentials           = new System.Net.NetworkCredential(sender, senderpassword);
                // client.DeliveryFormat = SmtpDeliveryFormat.SevenBit,
                client.DeliveryMethod = SmtpDeliveryMethod.Network;

                mailmsg.IsBodyHtml = true;
                ////false if the message body contains code
                mailmsg.Priority = System.Net.Mail.MailPriority.High;
                mailmsg.Subject  = subject;
                mailmsg.Body     = body;
                client.Send(mailmsg);

                mailmsg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                //Dim i As Integer = mailmsg.DeliveryNotificationOptions
                mailmsg.Attachments.Clear();
                mailmsg.Dispose();
                flag = true;
            }
            catch (Exception ex)
            {
                // Throw New SmtpFailedRecipientException("The following problem occurred when attempting to " + "send your email: " + ex.Message)
                return(false);
            }
            finally
            {
                mailmsg = null;
            }

            return(true);
        }
Example #52
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 #53
0
        public string SMTPEvent(eAppointment appointment)
        {
            if (appointment.Email.Count() > 0)
            {
                MailMessage msg = new MailMessage();
                foreach (var recepient in appointment.Email)
                {
                    msg.To.Add(recepient);
                }
                msg.From       = new MailAddress("*****@*****.**", "Canarys Automation Pvt ltd.");
                msg.Subject    = appointment.Subject;
                msg.Body       = appointment.Body;
                msg.IsBodyHtml = true;


                StringBuilder str = new StringBuilder();

                str.AppendLine("BEGIN:VCALENDAR");
                str.AppendLine("PRODID:-//Schedule a Meeting");
                str.AppendLine("VERSION:2.0");
                str.AppendLine("METHOD:REQUEST");
                str.AppendLine("BEGIN:VEVENT");
                str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", appointment.Start));
                str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
                str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", appointment.End));
                str.AppendLine("LOCATION: " + appointment.Location);
                str.AppendLine(string.Format("UID:{0}", Guid.NewGuid()));
                str.AppendLine(string.Format("DESCRIPTION:{0}", msg.Body));
                str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body));
                str.AppendLine(string.Format("SUMMARY:{0}", "Visit Created"));
                str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", "*****@*****.**"));
                str.AppendLine("BEGIN:VALARM");
                str.AppendLine("TRIGGER:-PT15M");
                str.AppendLine("ACTION:DISPLAY");
                str.AppendLine("DESCRIPTION:Reminder");
                str.AppendLine("END:VALARM");
                str.AppendLine("END:VEVENT");
                str.AppendLine("END:VCALENDAR");


                byte[]       byteArray = Encoding.ASCII.GetBytes(str.ToString());
                MemoryStream stream    = new MemoryStream(byteArray);


                System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(stream, "Visit Invite.ics");
                msg.Attachments.Add(attach);


                System.Net.Mime.ContentType contype = new System.Net.Mime.ContentType("text/calendar");
                contype.Parameters.Add("method", "REQUEST");
                //  contype.Parameters.Add("name", "Meeting.ics");
                AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), contype);
                AlternateView HTMLV = AlternateView.CreateAlternateViewFromString(msg.Body, new System.Net.Mime.ContentType("text/html"));
                msg.AlternateViews.Add(avCal);
                msg.AlternateViews.Add(HTMLV);


                try
                {
                    //Now sending a mail with attachment ICS file.
                    System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient();
                    smtpclient.Host        = "smtp.gmail.com"; //-------this has to given the Mailserver IP
                    smtpclient.Port        = 587;
                    smtpclient.EnableSsl   = true;
                    smtpclient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Canarys123");
                    smtpclient.Send(msg);
                    return("Success");
                }
                catch (System.Exception)
                {
                    return("Fail");
                }
            }
            return("No Recepient Found");
        }
Example #54
0
        public bool SendEMail()
        {
            bool   rtn = false;
            string msg = "1";

            msg = checkAllEmailAddress();

            if (msg != "1")
            {
                return(false);
            }
            mail.From = new MailAddress(_from);

            IndividualToAdd(ref mail, _to);
            if (string.IsNullOrEmpty(_cc) == false)
            {
                IndividualCCAdd(ref mail, _cc);
            }
            if (string.IsNullOrEmpty(_bcc) == false)
            {
                IndividualBCCAdd(ref mail, _bcc);
            }

            mail.Subject    = _subject;
            mail.IsBodyHtml = true;
            mail.Body       = _body;

            if (((_attachments != null)))
            {
                foreach (string attach_loopVariable in _attachments)
                {
                    string attachmentPath = attach_loopVariable;

                    System.Net.Mail.Attachment inline = new System.Net.Mail.Attachment(attachmentPath);
                    inline.ContentDisposition.Inline          = true;
                    inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                    //inline.ContentId = contentID;
                    inline.ContentType.MediaType = "image/png";
                    inline.ContentType.Name      = Path.GetFileName(attachmentPath);
                    mail.Attachments.Add(inline);
                }
            }

            try
            {
                smtp.Send(mail);
                //string token = "message";
                //smtp.SendAsync(mail, token);
                smtp = null;
                foreach (System.Net.Mail.Attachment aAttach in mail.Attachments)
                {
                    aAttach.Dispose();
                }
                mail.Attachments.Dispose();
                mail.Dispose();
                mail = null;
                rtn  = true;
            }
            catch (Exception e)
            {
                rtn = false;
                //throw ex;
            }
            return(rtn);
        }
Example #55
0
        public void SendEmail(string pTo, string pCc, string pBcc, string pSubject, string pBody, List <string> pAttachments)
        {
            try
            {
                var portNumber  = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SendEmailPortNo"]);
                var enableSSL   = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["SendEmailEnableSSL"]);
                var smtpAddress = Convert.ToString(ConfigurationManager.AppSettings["SendEmailSMTP"]);

                var FromMailAddress = System.Configuration.ConfigurationManager.AppSettings["SendEmailFrom"].ToString();
                var password        = System.Configuration.ConfigurationManager.AppSettings["SendEmailFromPassword"].ToString();

                //SmtpClient _client = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"]);
                var client = new SmtpClient(smtpAddress, portNumber) //Port 8025, 587 and 25 can also be used.
                {
                    Credentials = new NetworkCredential(FromMailAddress, password),
                };
                client.UseDefaultCredentials = false;
                MailMessage _mailMessage = new MailMessage();
                _mailMessage.To.Add(new MailAddress(pTo));
                _mailMessage.From       = new MailAddress(FromMailAddress, "GeneInsure");
                _mailMessage.Subject    = pSubject;
                _mailMessage.IsBodyHtml = true;

                if (pAttachments != null && pAttachments.Count > 0)
                {
                    if (pAttachments[0] != "")
                    {
                        foreach (var item in pAttachments)
                        {
                            System.Net.Mail.Attachment attachment;
                            attachment = new System.Net.Mail.Attachment(System.Web.HttpContext.Current.Server.MapPath(item.ToString()));
                            _mailMessage.Attachments.Add(attachment);
                        }
                    }
                }

                AlternateView plainView = AlternateView.CreateAlternateViewFromString(pBody, null, "text/plain");
                AlternateView htmlView  = AlternateView.CreateAlternateViewFromString(pBody, null, "text/html");
                _mailMessage.AlternateViews.Add(plainView);
                _mailMessage.AlternateViews.Add(htmlView);
                using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                {
                    smtp.Credentials = new NetworkCredential(FromMailAddress, password);
                    smtp.EnableSsl   = enableSSL;
                    try
                    {
                        smtp.Send(_mailMessage);
                    }
                    catch (Exception ex)
                    {
                        WriteLog(ex.Message);
                    }
                }
                //populateMailAddresses(pTo, _message.To);

                //if (pCc != null && pCc != "")
                //    populateMailAddresses(pCc, _message.CC);
                //if (pBcc != null && pBcc != "")
                //    populateMailAddresses(pBcc, _message.Bcc);
                //_message.Body = pBody;
                //_message.BodyEncoding = System.Text.Encoding.UTF8;
                //_message.Subject = pSubject;
                //_message.SubjectEncoding = System.Text.Encoding.UTF8;
                //_message.IsBodyHtml = pIsHTML;
                //if (pAttachments != null)
                //{
                //    foreach (string _str in pAttachments)
                //        _message.Attachments.Add(new Attachment(_str));
                //}
                //client.Send(_message);
                //_message.Dispose();
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }
Example #56
0
        static void Main(string[] args)
        {
            string content = "";
            string P1      = args[0]; //appel du nom de dossier et le stocker dans P1
            string path    = args[0];

            var    appSettings  = ConfigurationManager.AppSettings;
            string LoginSmtp    = appSettings["LoginSMTP"];
            string PasswordSMTP = appSettings["PasswordSMTP"];
            string file1        = appSettings["File1"];
            string file2        = appSettings["File2"];

            P1 = P1.Substring(P1.LastIndexOf("\\") + 1);


            FileInfo fi  = new FileInfo(@"" + args[0] + "\\" + file1);// on stock les infos du fichier LogsOF dans la varable fi
            FileInfo fic = new FileInfo(@"" + args[0] + "\\" + file2);

            DateTime a = fi.LastWriteTime;//la variable a contient l'heure de modfif du fichier LogsOF
            DateTime b = fic.LastWriteTime;

            //Console.WriteLine("fi : {0} , Fic :  {1}", a, b);
            //Console.ReadKey();

            if (!File.Exists(@"" + args[0] + "\\modif.txt"))
            {
                StreamWriter file = new StreamWriter(@"" + args[0] + "\\modif.txt");

                file.Close();
            }


            string[] tab = File.ReadAllLines(@"" + args[0] + "\\modif.txt"); // On stock dans tab ce que contient le doc.txt
            string   x;                                                      // création d'une variable qui nous permet de stocker la dernière heure de modfication d'un des deux fichiers



            if (a < b)
            {
                x = b.ToString();// si l'heure de modif de LogsOF.txt est inférieur à celle de logtoolsSplit_Bj_Files.txt alors la variable x prend la valeur de b
            }
            else
            {
                x = a.ToString();
            }



            int i = 0;

            for (i = 0; i < tab.Length; i++)
            {
                string val     = tab[i];
                string dossier = val.Substring(val.LastIndexOf(";") + 1);


                if (P1 == dossier)
                {
                    content = val.Substring(0, val.LastIndexOf(";"));


                    if (x != content)
                    {
                        tab[i] = (x + ";" + dossier);
                    }
                }
            }



            if (x != content)
            {
                //File.Delete(@"" + args[0] + "\\modif.txt");
                File.WriteAllLines(@"" + args[0] + "\\modif.txt", tab); // si l'heure de modif d'un des deux fichiers est différente de celle qu'on a sauvegardé alors on la remplace à la place de celle que l'on avait sauvegardé dans le fichier modifopenflux.txt

                try                                                     // envoie du mail
                {
                    MailMessage email = new MailMessage();
                    email.To.Add("*****@*****.**");

                    //email.CC.Add("*****@*****.**");
                    email.From    = new MailAddress("*****@*****.**");
                    email.Subject = "Les Logs Openflux SAGE CSI ont été modifiés";
                    email.Body    = "Voici les fichiers concernés";
                    System.Net.Mail.Attachment attachment;
                    System.Net.Mail.Attachment attachment2;
                    attachment  = new System.Net.Mail.Attachment(args[0] + "\\" + file1);
                    attachment2 = new System.Net.Mail.Attachment(args[0] + "\\" + file2);
                    email.Attachments.Add(attachment);
                    email.Attachments.Add(attachment2);
                    email.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host        = "smtp.gmail.com";
                    smtp.Credentials = new System.Net.NetworkCredential(LoginSmtp, PasswordSMTP);
                    smtp.Port        = 587;

                    smtp.EnableSsl = true;
                    smtp.Send(email);
                }
                catch (Exception ex)
                {
                    string[] contents = { ("Exception in sendEmail:" + ex.Message) };
                    //Console.WriteLine(contents[0]);
                    //Console.ReadKey();
                }
            }
        }
        public IActionResult SendMail(Mail MailDetails)
        {
            try
            {
                using (MailMessage EMail = new MailMessage())
                {
                    MailAddress fromAddress = new MailAddress(MailDetails.Sender, "From LTI");
                    List <System.Net.Mail.Attachment> mailattachment = new List <System.Net.Mail.Attachment>();
                    EMail.From = fromAddress;
                    if (!string.IsNullOrEmpty(MailDetails.To))
                    {
                        foreach (string email in MailDetails.To.Split(','))
                        {
                            if (!string.IsNullOrEmpty(email))
                            {
                                try
                                {
                                    EMail.To.Add(email);
                                }
                                catch { }
                            }
                        }
                    }
                    if (EMail.To.Count == 0)
                    {
                        throw new Exception("To address is not present in the mail");
                    }
                    if (!string.IsNullOrEmpty(MailDetails.CC))
                    {
                        foreach (string email in MailDetails.CC.Split(','))
                        {
                            if (!string.IsNullOrEmpty(email))
                            {
                                try
                                {
                                    EMail.CC.Add(email);
                                }
                                catch { }
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(MailDetails.BCC))
                    {
                        foreach (string email in MailDetails.BCC.Split(','))
                        {
                            if (!string.IsNullOrEmpty(email))
                            {
                                try
                                {
                                    EMail.Bcc.Add(email);
                                }
                                catch { }
                            }
                        }
                    }

                    if (MailDetails.Attachments != null && MailDetails.Attachments.Any())
                    {
                        foreach (var attachment in MailDetails.Attachments)
                        {
                            var contentType     = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
                            var emailAttachment = new System.Net.Mail.Attachment(attachment.Value, contentType);
                            emailAttachment.ContentDisposition.FileName = attachment.Key;
                            EMail.Attachments.Add(emailAttachment);
                        }
                    }


                    EMail.IsBodyHtml = true;
                    EMail.Body       = MailDetails.Body;
                    EMail.Subject    = MailDetails.Subject;

                    using (SmtpClient smtpClient = new SmtpClient())
                    {
                        //  smtpClient.Host = "smtp.office365.com";
                        smtpClient.Host = "smtp.gmail.com";
                        //  smtpClient.EnableSsl = false;
                        smtpClient.Port = 587;
                        // smtpClient.Port = 25;
                        smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                        smtpClient.UseDefaultCredentials = false;
                        //   smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Lnt@0987654");
                        smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Gmailpass@1995");
                        smtpClient.EnableSsl   = true;
                        smtpClient.Timeout     = 6000000;
                        smtpClient.Send(EMail);
                    }
                    MailDetails.Status = "Success";
                    // return Content(HttpStatusCode.OK, true);
                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                MailDetails.Status = "Fail";
                return(BadRequest(ex.Message.ToString()));
            }
        }
Example #58
0
        private void UploadNotesAsMails(string folder, List <Note> notesEvernote, string exportFile)
        {
            int uploadcount = 0;

            foreach (Note n in notesEvernote)
            {
                if (n.Action == NoteAction.UploadToIMAP)
                {
                    uploadcount++;
                }
            }

            int counter = 0;

            foreach (Note n in notesEvernote)
            {
                if (cancelled)
                {
                    break;
                }

                if (n.Action == NoteAction.UploadToIMAP)
                {
                    SetInfo(null, string.Format("uploading note ({0} of {1}) : \"{2}\"", counter + 1, uploadcount, n.Title), counter++, uploadcount);

                    XmlTextReader xtrInput;
                    XmlDocument   xmlDocItem;

                    xtrInput = new XmlTextReader(exportFile);

                    while (xtrInput.Read())
                    {
                        while ((xtrInput.NodeType == XmlNodeType.Element) && (xtrInput.Name.ToLower() == "note"))
                        {
                            if (cancelled)
                            {
                                break;
                            }

                            xmlDocItem = new XmlDocument();
                            xmlDocItem.LoadXml(xtrInput.ReadOuterXml());
                            XmlNode node = xmlDocItem.FirstChild;

                            // node is <note> element
                            // node.FirstChild.InnerText is <title>
                            node = node.FirstChild;

                            if (node.InnerText == n.Title)
                            {
                                node = node.NextSibling;
                                if (n.Content == node.InnerXml.Replace("\r", string.Empty))
                                {
                                    XmlNodeList atts = xmlDocItem.GetElementsByTagName("resource");
                                    foreach (XmlNode xmln in atts)
                                    {
                                        Attachment attachment = new Attachment();
                                        attachment.Base64Data = xmln.FirstChild.InnerText;
                                        byte[] data    = Convert.FromBase64String(xmln.FirstChild.InnerText);
                                        byte[] hash    = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(data);
                                        string hashHex = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();

                                        attachment.Hash = hashHex;

                                        XmlNodeList fns = xmlDocItem.GetElementsByTagName("file-name");
                                        if (fns.Count > n.Attachments.Count)
                                        {
                                            attachment.FileName = fns.Item(n.Attachments.Count).InnerText;
                                        }

                                        XmlNodeList mimes = xmlDocItem.GetElementsByTagName("mime");
                                        if (mimes.Count > n.Attachments.Count)
                                        {
                                            attachment.ContentType = mimes.Item(n.Attachments.Count).InnerText;
                                        }

                                        n.Attachments.Add(attachment);
                                    }
                                }
                            }
                        }
                    }

                    xtrInput.Close();

                    string htmlBody = n.Content;

                    List <LinkedResource>             linkedResources   = new List <LinkedResource>();
                    List <System.Net.Mail.Attachment> attachedResources = new List <System.Net.Mail.Attachment>();
                    foreach (Attachment attachment in n.Attachments)
                    {
                        Regex rx = new Regex(@"<en-media\b[^>]*?hash=""" + attachment.Hash + @"""[^>]*/>", RegexOptions.IgnoreCase);
                        if ((attachment.ContentType != null) && (attachment.ContentType.Contains("image") && rx.Match(htmlBody).Success))
                        {
                            // replace the <en-media /> tag with an <img /> tag
                            htmlBody = rx.Replace(htmlBody, @"<img src=""cid:" + attachment.Hash + @"""/>");
                            byte[]      data = Convert.FromBase64String(attachment.Base64Data);
                            Stream      s    = new MemoryStream(data);
                            ContentType ct   = new ContentType();
                            ct.Name      = attachment.FileName;
                            ct.MediaType = attachment.ContentType;
                            LinkedResource lr = new LinkedResource(s, ct);
                            lr.ContentId = attachment.Hash;
                            linkedResources.Add(lr);
                        }
                        else
                        {
                            byte[]      data = Convert.FromBase64String(attachment.Base64Data);
                            Stream      s    = new MemoryStream(data);
                            ContentType ct   = new ContentType();
                            ct.Name      = attachment.FileName != null ? attachment.FileName : string.Empty;
                            ct.MediaType = attachment.ContentType != null ? attachment.ContentType : string.Empty;
                            System.Net.Mail.Attachment a = new System.Net.Mail.Attachment(s, ct);
                            attachedResources.Add(a);
                        }
                    }

                    htmlBody = htmlBody.Replace(@"<![CDATA[<?xml version=""1.0"" encoding=""UTF-8""?>", string.Empty);
                    htmlBody = htmlBody.Replace(@"<!DOCTYPE en-note SYSTEM ""http://xml.evernote.com/pub/enml2.dtd"">", string.Empty);
                    htmlBody = htmlBody.Replace("<en-note>", "<body>");
                    htmlBody = htmlBody.Replace("</en-note>]]>", "</body>");
                    htmlBody = htmlBody.Trim();
                    htmlBody = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN""><head></head>" + htmlBody;
                    MailMessage mailMsg = new MailMessage();

                    AlternateView altViewHtml = AlternateView.CreateAlternateViewFromString(htmlBody, Encoding.UTF8, MediaTypeNames.Text.Html);
                    foreach (LinkedResource lr in linkedResources)
                    {
                        altViewHtml.LinkedResources.Add(lr);
                    }

                    // Add the alternate views instead of using MailMessage.Body
                    mailMsg.AlternateViews.Add(altViewHtml);
                    foreach (System.Net.Mail.Attachment a in attachedResources)
                    {
                        mailMsg.Attachments.Add(a);
                    }

                    mailMsg.From = new MailAddress("EveImSync <*****@*****.**>");
                    mailMsg.To.Add(new MailAddress("EveImSync <*****@*****.**>"));
                    mailMsg.Subject = n.Title;
                    string eml = mailMsg.GetEmailAsString();

                    Regex rex = new Regex(@"^date:(.*)$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    eml = rex.Replace(eml, "Date: " + n.Date.ToString("ddd, dd MMM yyyy HH:mm:ss K"));

                    // find the folder to upload to
                    string tagfolder = folder;
                    if (n.Tags.Count > 0)
                    {
                        tagfolder = tagfolder + "/" + n.Tags[0];
                    }

                    IFolder currentFolder = GetOrCreateFolderByPath(tagfolder);
                    string  customFlag    = "xeveim" + n.ContentHash;

                    // now upload the new note
                    int numMsg = currentFolder.Messages.Length;
                    client.RequestManager.SubmitAndWait(new AppendRequest(eml, customFlag, currentFolder, null), false);

                    if (n.Tags.Count > 1)
                    {
                        IMessage[] oldMsgs = client.MailboxManager.GetMessagesByFolder(currentFolder);
                        client.RequestManager.SubmitAndWait(new MessageListRequest(currentFolder, null), false);
                        IMessage[] newMsgs = client.MailboxManager.GetMessagesByFolder(currentFolder);
                        IMessage   newMsg  = null;
                        foreach (IMessage imsg in newMsgs)
                        {
                            bool found = false;
                            foreach (IMessage omsg in oldMsgs)
                            {
                                if (imsg.UID == omsg.UID)
                                {
                                    found = true;
                                    break;
                                }
                            }

                            if (!found)
                            {
                                newMsg = client.MailboxManager.GetMessageByUID(imsg.UID, currentFolder.ID);
                                break;
                            }
                        }

                        // copy the email to all tag folders
                        for (int i = 1; i < n.Tags.Count; ++i)
                        {
                            if (cancelled)
                            {
                                break;
                            }

                            tagfolder = folder + "/" + n.Tags[i];
                            IFolder tagFolder = GetOrCreateFolderByPath(tagfolder);

                            client.RequestManager.SubmitAndWait(new CopyMessageRequest(newMsg, tagFolder, null), true);
                            client.RequestManager.SubmitAndWait(new MessageListRequest(tagFolder, null), true);
                        }
                    }
                }
            }
        }
Example #59
0
        private void Btn_enviar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                short  proveedor = 0;
                string nombre    = string.Empty;
                string correo    = string.Empty;

                Producto_Proveedor prp = new Producto_Proveedor();

                if (prp.ReadCompra(id).Count > 0)
                {
                    Compra_Proveedor cop = new Compra_Proveedor()
                    {
                        ID_COMPRA = id
                    };

                    if (cop.Read())
                    {
                        proveedor = cop.ID_PROVEEDOR;
                    }

                    Proveedor pro = new Proveedor()
                    {
                        ID_PROVEEDOR = proveedor
                    };

                    if (pro.Read())
                    {
                        nombre = pro.NOMBRE_PROVEEDOR;
                        correo = pro.CORREO;
                    }

                    string periodo = DateTime.Now.ToString("ddMMyyyy");
                    dtg_producto.SelectAllCells();
                    dtg_producto.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
                    ApplicationCommands.Copy.Execute(null, dtg_producto);
                    String resultat = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
                    String result   = (string)Clipboard.GetData(DataFormats.Text);
                    dtg_producto.UnselectAllCells();
                    System.IO.StreamWriter file1 = new System.IO.StreamWriter(@"C:\productos\" + nombre + "_" + periodo + ".xls");
                    file1.WriteLine(result.Replace(',', ' '));
                    file1.Close();

                    MailMessage mail = new MailMessage();

                    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                    //Correo origen
                    mail.From = new MailAddress("*****@*****.**");
                    //Correo destino
                    mail.To.Add(correo);
                    //Asunto
                    mail.Subject = "Ferretria Ferme - Orden de productos";
                    //Detalle del correo
                    StringBuilder sbBody = new StringBuilder();
                    //Cada uno es una línea
                    sbBody.AppendLine("Estimado " + nombre + ",");

                    sbBody.AppendLine("Ferreteria Ferme ha solicitado los productos adjuntados en el archivo excel");

                    sbBody.AppendLine("Saludos Cordiales");

                    sbBody.AppendLine("Ferreteria Ferme");

                    mail.Body = sbBody.ToString();
                    //Archivo adjunto
                    System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(@"C:\productos\" + pro.NOMBRE_PROVEEDOR + "_" + periodo + ".xls");

                    mail.Attachments.Add(attachment);

                    //RECORDATORIO: Colocar contraseña
                    SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "");

                    SmtpServer.Port      = 587;
                    SmtpServer.EnableSsl = true;

                    SmtpServer.Send(mail);
                    MessageBox.Show("Orden enviada");
                }

                else
                {
                    MessageBoxResult mal = MessageBox.Show("Debe ingresar al menos un producto para enviar la solicitud",
                                                           "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Example #60
0
    protected static void SimpleEmail(string from_address, string from_name, string to, string subject, string body, bool isHTML,
                                      string smtp_host, int smtp_port, string accountUsername, string accountPassword, string[] attachments, System.Net.Mail.AlternateView[] alternativeViews)
    {
        if (isHTML && to.Contains(ConfigurationManager.AppSettings["EmailStringMatchToConvertToPlainText"]))
        {
            body   = HtmlConverter.HTMLToText(body);
            isHTML = false;
        }


        System.Net.Mail.Attachment[] list = null;

        try
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
            message.From = new System.Net.Mail.MailAddress(from_address, from_name);
            foreach (string _to in to.Split(','))
            {
                message.To.Add(_to.Trim());
            }
            message.Subject    = subject;
            message.Body       = body;
            message.IsBodyHtml = isHTML;

            if (alternativeViews != null)
            {
                for (int i = 0; i < alternativeViews.Length; i++)
                {
                    message.AlternateViews.Add(alternativeViews[i]);
                }
            }


            if (attachments != null && attachments.Length > 0)
            {
                list = new System.Net.Mail.Attachment[attachments.Length];
                for (int i = 0; i < attachments.Length; i++)
                {
                    list[i] = new System.Net.Mail.Attachment(attachments[i]);
                    message.Attachments.Add(list[i]);
                }
            }

            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtp_host, smtp_port);
            if (accountUsername.Length > 0 || accountPassword.Length > 0)
            {
                smtp.Credentials = new System.Net.NetworkCredential(accountUsername, accountPassword);
            }
            else
            {
                smtp.UseDefaultCredentials = false;

                // turn off validating certificate because it is throwing an error when using anonymous sending
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificates.X509Certificate certificate, X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true); };
            }

            smtp.Timeout = 300000; // 300 sec = 5 mins

            smtp.EnableSsl = true;
            smtp.Send(message);
        }
        catch (Exception ex)
        {
            Logger.LogException(ex, false); // cant email it again if emailing is failing..
        }
        finally
        {
            // unlock the files they reference
            if (list != null)
            {
                for (int i = 0; i < list.Length; i++)
                {
                    list[i].Dispose();
                }
            }
        }
    }