Beispiel #1
1
        public bool SendEmail(byte[] image, string emailTo = "*****@*****.**")
        {
            try
            {
                SmtpClient smtp = new SmtpClient();

                MailMessage message = new System.Net.Mail.MailMessage();
                message.To.Add(new MailAddress(emailTo));
                message.Subject = "Image";

                System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
                contentType.MediaType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
                contentType.Name = "image.jpeg";

                using (MemoryStream stream = new MemoryStream(image))
                using (MemoryStream emptyStream = new MemoryStream())
                {
                    Image.FromStream(stream).Save(emptyStream, ImageFormat.Jpeg);
                    emptyStream.Seek(0, SeekOrigin.Begin);
                    Attachment attachment = new Attachment(emptyStream, contentType);
                    message.Attachments.Add(attachment);
                    smtp.Send(message);
                }

                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(e.Message);
                return false;
            }
        }
        public virtual dynamic Post(AuthRequestModel model)
        {
            var request = new RestRequest(Method.POST);
            if (string.IsNullOrEmpty(model.client_id))
            {
                model.client_id = ClientId;
            }
            if (string.IsNullOrEmpty(model.grant_type) && GrantTypeDetection)
            {
                model.grant_type = DetectGrantType(model);
            }
            request.AddJsonBody(model);

            var response = restClient.Execute<AuthorizationResponse>(request);
            if (response.ErrorException == null && response.StatusCode.Equals(HttpStatusCode.OK))
            {
                return Json(response.Data);
            }
            else
            {
                var responseProxy = new HttpResponseMessage(response.StatusCode);
                var mimeType = new System.Net.Mime.ContentType(response.ContentType);
                responseProxy.Content = new StringContent(response.Content, System.Text.Encoding.GetEncoding(mimeType.CharSet), mimeType.MediaType);
                return responseProxy;
            }
        }
        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);
        }
        public void attachExcelFileToMail(String fileToAttach, String fileName)
        {
            byte[] fileInBytes = fileToByteArray(fileToAttach);
            MemoryStream ms = new MemoryStream(fileInBytes);
            ms.Position = 0;
            var contentType = new System.Net.Mime.ContentType("application/vnd.ms-excel");
            this.attachement = new Attachment(ms, contentType);
            this.attachement.ContentDisposition.FileName = fileName;

        }
Beispiel #5
0
        public void SendMail(string Subject ,string Body, string To , string Attachment_FileName)
        {
            //SendMail(new string[]{Subject,Body,To,Attachment_FileName});

                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                if (_sendCopyToSender)
                    message.To.Add(new MailAddress(_From, _nameFrom));

                message.From = new MailAddress(_From, _nameFrom);
                message.IsBodyHtml = false;

                message.BodyEncoding = Encoding.GetEncoding("KOI8-R");
                //message.AlternateViews.Add(new AlternateView(


                message.Subject = Subject;
                message.Bcc.Add(To);

                SmtpClient client = new SmtpClient(_smtpAdress);
                client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;


                message.Body = Body;
                
                System.Net.Mime.ContentType cType = new System.Net.Mime.ContentType("application/vnd.ms-excel");


                if (!String.IsNullOrEmpty(Attachment_FileName))
                {

                    cType.Name = System.IO.Path.GetFileName(Attachment_FileName.Trim());
                    Attachment data = new Attachment(Attachment_FileName.Trim(), cType);
                    System.Net.Mime.ContentDisposition disposition = data.ContentDisposition;
                    disposition.FileName = cType.Name;
                    disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;


                    message.Attachments.Add(data);

                }

                try
                {
                    client.Send(message);
                    Log("Mail succesully sended to " + To);
                }
                catch (Exception err)
                {
                    Log(String.Format("err={0},Subject={1},Body = {2}, To={3}, Attach={4}"
                        ,err.ToString(),Subject,Body,To,Attachment_FileName));
                    throw;
                }
            
        }
Beispiel #6
0
        /// <summary>
        /// Converts a content type to a ResourceFormat
        /// </summary>
        /// <param name="contentType">The content type, as it appears on e.g. a Http Content-Type header</param>
        /// <returns></returns>
        public static ResourceFormat GetResourceFormatFromContentType(string contentType)
        {
            if (String.IsNullOrEmpty(contentType)) return ResourceFormat.Unknown;

            var f = new System.Net.Mime.ContentType(contentType).MediaType.ToLowerInvariant();

            if (JSON_CONTENT_HEADERS.Contains(f))
                return ResourceFormat.Json;
            else if (XML_CONTENT_HEADERS.Contains(f))
                return ResourceFormat.Xml;
            else
                return ResourceFormat.Unknown;
        }
Beispiel #7
0
        public static bool CreateAppointment(string SendFrom, string SendTo, string Subject, string Body, string Location, System.DateTime StartTime, System.DateTime EndTime, string MsgID, int Sequence, bool IsCancelled,
        SmtpServer Server)
        {
            dynamic result = false;
            try
            {
                if (string.IsNullOrEmpty(SendTo) || string.IsNullOrEmpty(SendFrom))
                {
                    throw new InvalidOperationException("SendFrom and SendTo email addresses must be specified.");
                }

                dynamic fromAddress = new MailAddress(SendFrom);
                dynamic toAddress = new MailAddress(SendTo);
                MailMessage mail = new MailMessage();

                var _with3 = mail;
                _with3.Subject = Subject;
                _with3.From = fromAddress;

                //Need to send to both parties to organize the meeting
                _with3.To.Add(toAddress);
                _with3.To.Add(fromAddress);

                //Use the text/calendar content type
                System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
                ct.Parameters.Add("method", "REQUEST");
                //Create the iCalendar format and add it to the mail
                dynamic cal = CreateICal(SendFrom, SendTo, Subject, Body, Location, StartTime, EndTime, MsgID, Sequence, IsCancelled);
                mail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(cal, ct));

                //Send the meeting request
                SmtpClient smtp = new SmtpClient(Server.SmtpServerName, Server.SmtpPort);
                smtp.Credentials = new NetworkCredential(Server.SmtpUserId, Server.SmtpPassword);
                smtp.Send(mail);

                result = true;

            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Failed to send Appointment.", ex);
            }

            return result;
        }
Beispiel #8
0
 public Attachment(string fileName, System.Net.Mime.ContentType contentType) : base(default(string))
 {
 }
 private AlternateView CreateHtmlView()
 {
     var contentType = new System.Net.Mime.ContentType("text/html");
     return AlternateView.CreateAlternateViewFromString(Package.HtmlBody, contentType);
 }
 protected virtual dynamic Proxy(RestRequest request)
 {
     var response = restClient.Execute(request);
     if (response.ErrorException == null && !string.IsNullOrEmpty(response.Content))
     {
         var responseProxy = new HttpResponseMessage(response.StatusCode);
         var mimeType = new System.Net.Mime.ContentType(response.ContentType);
         responseProxy.Content = new StringContent(response.Content, System.Text.Encoding.GetEncoding(mimeType.CharSet), mimeType.MediaType);
         return responseProxy;
     }
     else if (response.ErrorException == null)
     {
         return new HttpResponseMessage(response.StatusCode);
     }
     else
     {
         var resposneProxy = new HttpResponseMessage(HttpStatusCode.InternalServerError);
         resposneProxy.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new { reason = response.ErrorException.Message }), System.Text.Encoding.UTF8, "application/json");
         return resposneProxy;
     }
 }
        protected void SendBtn_Click(object sender, EventArgs e)
        {
            bool isOK = true;
            string UserEmail = "";
            string UserID = "";
            string FromName = "";

            if (string.IsNullOrEmpty(Message.Text)) isOK = false;
            if (Recipient.SelectedValue.ToString() == "0") isOK = false;

            HttpCookie myTestCookie = new HttpCookie("UKFilmLocationAdmin");
            myTestCookie = Request.Cookies["UKFilmLocationAdmin"];

            // Read the cookie information and display it.
            if (myTestCookie != null)
            {
                UserEmail = myTestCookie.Value;
            }
            else isOK = false;

            if (!isOK) ErrorLabel.Text = "<div class=\"alert alert-danger\" role=\"alert\"><strong>Send Failed!</strong> Please check the details and try again.</div>";
            else
            {

                // Update or Create Record

                DBConnection = new MySqlConnection(objUKFilmLocation.DBConnect);
                DBCommand = DBConnection.CreateCommand();
                DBConnection.Open();

                // Get UserDetails

                DBCommand.CommandText = "select * from UserDetails where Email = '" + myTestCookie.Value + "';";

                DBResult = DBCommand.ExecuteReader();

                if (DBResult.Read())
                {
                    UserID = DBResult["UserID"].ToString();
                    FromName = DBResult["FirstName"].ToString() + " " + DBResult["LastName"].ToString();
                }

                DBConnection.Close();
                DBConnection.Open();

                // Create Record
                DBCommand.CommandText = "insert into Messages set FromUserID = '" + UK_Film_Location_Class.UKFilmLocation.makeSQLSafe(UserID) + "', Message = '" + UK_Film_Location_Class.UKFilmLocation.makeSQLSafe(Message.Text) + "', Seen = 0, ToUserID = '" + UK_Film_Location_Class.UKFilmLocation.makeSQLSafe(Recipient.SelectedValue.ToString()) + "', DateSent = '" + UK_Film_Location_Class.UKFilmLocation.makeSQLDate(DateTime.Now.ToString()) + "';";

                DBCommand.ExecuteNonQuery();

                DBConnection.Close();

                // send email

                DBConnection.Open();

                // Get UserDetails

                string ToEmail = "";

                DBCommand.CommandText = "select * from UserDetails where UserID = '" + Recipient.SelectedValue.ToString() + "';";

                DBResult = DBCommand.ExecuteReader();

                if (DBResult.Read())
                {
                    ToEmail = DBResult["Email"].ToString();
                }

                DBConnection.Close();

                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.IsBodyHtml = true;

                message.To.Add(ToEmail);

                message.From = new System.Net.Mail.MailAddress(myTestCookie.Value, FromName);

                message.Subject = "System Message";

                message.Body = Message.Text + "<br><br>" + FromName;

                System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType("text/html");

                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(UK_Film_Location_Class.UKFilmLocation.DefaultMailServer);
                smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "ch0c0late10");

                smtp.Send(message);

                DBConnection.Dispose();

                Response.Redirect("/dashboard.aspx");
            }
        }
Beispiel #12
0
        public static bool SendEmail(string addrFrom, string addrTo, string subject, string textBody, string htmlBody)
        {
            var smtp = new SmtpClient("localhost");
            /*var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(addrFrom, "mtx$l0cK")
            };*/

            var addr_from = new MailAddress(addrFrom);
            var addr_to = new MailAddress(addrTo);

            try {
                using (var message = new MailMessage(addr_from, addr_to)) {
                    var mime_type = new System.Net.Mime.ContentType ("text/html");
                    var html_view = AlternateView.CreateAlternateViewFromString (htmlBody, mime_type);

                    message.Subject = subject;
                    message.BodyEncoding =  System.Text.Encoding.UTF8;
                    message.SubjectEncoding =  System.Text.Encoding.UTF8;
                    message.IsBodyHtml = false;
                    message.Body = textBody;
                    message.AlternateViews.Add (html_view);

                    smtp.Send (message);
                }

                return true;
            } catch(Exception e) {
                Console.Error.WriteLine (e);
            }

            return false;
        }
        public static void SendEmailAppointment(DateTime startDate, DateTime endDate, string subject, string summary, string location, string attendeeName, string attendeeEmail, string organizerName, string organizerEmail, string uniqueIdentifier)
        {
            // Send the calendar message to the attendee

            MailMessage loMsg = new MailMessage();
            AlternateView loTextView = null;
            AlternateView loHTMLView = null;
            AlternateView loCalendarView = null;
            SmtpClient loSMTPServer = new SmtpClient();

            // SMTP settings set up in web.config such as:
            //  <system.net>
            //   <mailSettings>
            //    <smtp>
            //     <network
            //       host = "exchange.mycompany.com"
            //       port = "25"
            //       userName = "******"
            //       password="******" />
            //    </smtp>
            //   </mailSettings>
            //  </system.net>

            // Set up the different mime types contained in the message
            System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
            System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
            System.Net.Mime.ContentType loCalendarType = new System.Net.Mime.ContentType("text/calendar");

            // Add parameters to the calendar header
            loCalendarType.Parameters.Add("method", "REQUEST");
            loCalendarType.Parameters.Add("name", "meeting.ics");

            // Create message body parts
            loTextView = AlternateView.CreateAlternateViewFromString(BodyText(startDate, endDate, subject, summary, location, attendeeName, attendeeEmail, organizerName, organizerEmail), loTextType);
            loMsg.AlternateViews.Add(loTextView);

            loHTMLView = AlternateView.CreateAlternateViewFromString(BodyHTML(startDate, endDate, subject, summary, location, attendeeName, attendeeEmail, organizerName, organizerEmail), loHTMLType);
            loMsg.AlternateViews.Add(loHTMLView);

            loCalendarView = AlternateView.CreateAlternateViewFromString(VCalendar(startDate, endDate, subject, summary, location, attendeeName, attendeeEmail, organizerName, organizerEmail, uniqueIdentifier), loCalendarType);
            loCalendarView.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
            loMsg.AlternateViews.Add(loCalendarView);

            // Adress the message

            loMsg.From = new MailAddress(organizerEmail);
            loMsg.To.Add(new MailAddress(attendeeEmail));
            loMsg.Subject = subject;

            // Send the message
            loSMTPServer.DeliveryMethod = SmtpDeliveryMethod.Network;
            loSMTPServer.Send(loMsg);
        }
Beispiel #14
0
 public LinkedResource(string fileName, System.Net.Mime.ContentType contentType) : base(default(string))
 {
 }
Beispiel #15
0
        public async Task SendAsAppointment(Ekilibrate.Model.Entity.General.clsMensajeCorreo mensaje,
                                            string MailAccount,
                                            string MailPassword,
                                            string Remitente,
                                            string Location,
                                            DateTime StarDate,
                                            DateTime EndDate
                                            )
        {
            try
            {
                Ekilibrate.ad.General.clsMensajeCorreo  objCorreo = new Ekilibrate.ad.General.clsMensajeCorreo(_lifetimeScope);
                Ekilibrate.Model.Common.ExecutionResult Result    = new Ekilibrate.Model.Common.ExecutionResult();
                bool enviado = false;

                // Now Contruct the ICS file using string builder
                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;TZID=America/Guatemala:{0:yyyyMMddTHHmmssZ}", StarDate));
                //str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", StarDate));
                str.AppendLine(string.Format("DTEND;TZID=America/Guatemala:{0:yyyyMMddTHHmmssZ}", EndDate));
                str.AppendLine("LOCATION: " + Location);
                str.AppendLine(string.Format("UID:{0}", Guid.NewGuid()));
                //str.AppendLine(string.Format("DESCRIPTION;ENCODING=ESCAPED-CHAR:{0}", mensaje.Mensaje));
                //str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", mensaje.Mensaje));
                str.AppendLine(string.Format("SUMMARY:{0}", mensaje.Asunto));
                str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", MailAccount));

                str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", Remitente, mensaje.Para));

                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");

                //Now sending a mail with attachment ICS file.
                System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient();
                smtpclient.Host = "localhost"; //-------this has to given the Mailserver IP

                smtpclient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

                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);

                using (SmtpClient client = new SmtpClient())
                {
                    client.EnableSsl             = false;
                    client.UseDefaultCredentials = false;
                    client.Credentials           = new NetworkCredential(MailAccount, MailPassword);
                    client.Host                     = "mail.server260.com";
                    client.Port                     = 587;
                    client.DeliveryMethod           = SmtpDeliveryMethod.Network;
                    client.ServicePoint.MaxIdleTime = 1;
                    client.Timeout                  = 10000;

                    MailMessage msg = new MailMessage();

                    msg.From = new MailAddress(MailAccount, Remitente);
                    msg.To.Add(mensaje.Para.ToString());
                    msg.Subject = mensaje.Asunto;
                    //msg.Body = mensaje.Mensaje;
                    msg.IsBodyHtml = mensaje.EsHTML.Equals("SI");
                    msg.Bcc.Add(MailAccount);
                    msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                    msg.AlternateViews.Add(avCal);

                    try
                    {
                        client.Send(msg);
                        enviado = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error al enviar mensaje: " + ex.Message);
                        //throw new Exception("No se pudo enviar el mensaje de confirmación a tu correo, favor verifica que sea correcto");
                    }

                    if (enviado)
                    {
                        mensaje.EstadoEnvio = "ENVIADO";
                        mensaje.FechaEnvio  = DateTime.Now;
                    }

                    await objCorreo.Insert(mensaje);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error al enviar correo: " + ex.Message + " / " + ex.InnerException.Message);
                throw;
            }
        }
Beispiel #16
0
		protected void GenerarButton_Click(object sender, EventArgs e)
		{
			if (((Button)sender).ID == "DescargarButton" && CedWebRN.Fun.NoEstaLogueadoUnUsuarioPremium((CedWebEntidades.Sesion)Session["Sesion"]))
			{
				if (!MonedaComprobanteDropDownList.Enabled)
				{
					ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Esta funcionalidad es exclusiva del SERVICIO PREMIUM.  Contáctese con Cedeira Software Factory para acceder al servicio.');</script>");
				}
				else
				{
					ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Su sesión ha caducado por inactividad. Por favor vuelva a loguearse.')</script>");
				}
			}
			else
			{
				try
				{
					FeaEntidades.InterFacturas.lote_comprobantes lote = GenerarLote();

					System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(lote.GetType());

					System.Text.StringBuilder sb = new System.Text.StringBuilder();
					sb.Append(lote.cabecera_lote.cuit_vendedor);
					sb.Append("-");
					sb.Append(lote.cabecera_lote.punto_de_venta.ToString("0000"));
					sb.Append("-");
					sb.Append(lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante.ToString("00"));
					sb.Append("-");
					sb.Append(lote.comprobante[0].cabecera.informacion_comprobante.numero_comprobante.ToString("00000000"));
					sb.Append(".xml");

					System.IO.MemoryStream m = new System.IO.MemoryStream();
					System.IO.StreamWriter sw = new System.IO.StreamWriter(m);
					sw.Flush();
					System.Xml.XmlWriter writerdememoria = new System.Xml.XmlTextWriter(m, System.Text.Encoding.GetEncoding("ISO-8859-1"));
					x.Serialize(writerdememoria, lote);
					m.Seek(0, System.IO.SeekOrigin.Begin);


					string smtpXAmb = System.Configuration.ConfigurationManager.AppSettings["Ambiente"].ToString();
					System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

					try
					{
						RegistrarActividad(lote, sb, smtpClient, smtpXAmb, m);
					}
					catch
					{
					}

					if (((Button)sender).ID == "DescargarButton")
					{
						//Descarga directa del XML
						System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(@"~/Temp/" + sb.ToString()), System.IO.FileMode.Create);
						m.WriteTo(fs);
						fs.Close();
						Server.Transfer("~/DescargaTemporarios.aspx?archivo=" + sb.ToString(), false);
					}
					else
					{
						//Envio por mail del XML
						System.Net.Mail.MailMessage mail;
						if (((CedWebEntidades.Sesion)Session["Sesion"]).Cuenta.Id != null)
						{
							mail = new System.Net.Mail.MailMessage("*****@*****.**",
								((CedWebEntidades.Sesion)Session["Sesion"]).Cuenta.Email,
								"Ced-eFact-Envío automático archivo XML:" + sb.ToString()
								, string.Empty);
						}
						else
						{
							mail = new System.Net.Mail.MailMessage("*****@*****.**",
								Email_VendedorTextBox.Text,
								"Ced-eFact-Envío automático archivo XML:" + sb.ToString()
								, string.Empty);
						}
						System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
						contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;
						contentType.Name = sb.ToString();
						System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(m, contentType);
						mail.Attachments.Add(attachment);
						mail.BodyEncoding = System.Text.Encoding.UTF8;
						mail.Body = Mails.Body.AgregarBody();
						smtpClient.Host = "localhost";
						if (smtpXAmb.Equals("DESA"))
						{
							string MailServidorSmtp = System.Configuration.ConfigurationManager.AppSettings["MailServidorSmtp"];
							if (MailServidorSmtp != "")
							{
								string MailCredencialesUsr = System.Configuration.ConfigurationManager.AppSettings["MailCredencialesUsr"];
								string MailCredencialesPsw = System.Configuration.ConfigurationManager.AppSettings["MailCredencialesPsw"];
								smtpClient.Host = MailServidorSmtp;
								if (MailCredencialesUsr != "")
								{
									smtpClient.Credentials = new System.Net.NetworkCredential(MailCredencialesUsr, MailCredencialesPsw);
								}
								smtpClient.Credentials = new System.Net.NetworkCredential(MailCredencialesUsr, MailCredencialesPsw);
							}
						}
						smtpClient.Send(mail);
					}
					m.Close();

					if (!smtpXAmb.Equals("DESA"))
					{
						ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Archivo enviado satisfactoriamente');window.open('https://srv1.interfacturas.com.ar/cfeWeb/faces/login/identificacion.jsp/', '_blank');</script>");
					}
					else
					{
						ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Archivo enviado satisfactoriamente');</script>");
					}
				}
				catch (Exception ex)
				{
					ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Problemas al generar el archivo.\\n " + ex.Message + "');</script>");
				}
			}
		}
Beispiel #17
0
        public ActionResult FF(HttpPostedFileBase file, System.Web.Mvc.FormCollection form1, FFAC model)
        {
            var MDclient              = new MongoClient("mongodb+srv://fred:" + MongoDBPW() + "@freefinancial-tubyw.azure.mongodb.net/QuickPoint?retryWrites=true&w=majority");
            var db                    = MDclient.GetDatabase("QuickPoint");
            var collec                = db.GetCollection <BsonDocument>("FreeFinancial");
            var dt                    = DateTime.Now.ToString();
            var username              = escapeCharacters((form1["name"].ToString()));
            var email                 = escapeCharacters((form1["email"].ToString()));
            var phone                 = escapeCharacters((form1["phone"].ToString()));
            var staffno               = escapeCharacters((form1["staffno"].ToString()));
            var turnover              = escapeCharacters((form1["turnover"].ToString()));
            var selected              = model.Business;
            var bookkeeping           = model.Bookkeeping;
            var payroll               = model.Payroll;
            var CompaniesHouseReturns = model.CompaniesHouseReturns;
            var SelfAssessment        = model.SelfAssessment;
            var VATReturns            = model.VATReturns;
            var AccountsManagement    = model.AccountsManagement;
            var BusinessConsultation  = model.BusinessConsultation;
            var TaxationAdvice        = model.TaxationAdvice;

            try
            {
                byte[] data;
                using (Stream inputStream = file.InputStream)
                    using (MemoryStream ms = new MemoryStream())
                        using (var client = new SmtpClient("smtp.office365.com", 587))
                            using (var message = new MailMessage(Utils.GetConfigSetting("Fredemail"), Utils.GetConfigSetting("LudaEmail")))
                            {
                                if (file != null)
                                {
                                    MemoryStream memoryStream = inputStream as MemoryStream;
                                    if (memoryStream == null)
                                    {
                                        memoryStream = new MemoryStream();
                                        inputStream.CopyTo(memoryStream);
                                    }
                                    data = memoryStream.ToArray();
                                    memoryStream.Position = 0;
                                    message.Attachments.Add(new Attachment(memoryStream, file.FileName, file.ContentType));
                                }

                                System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Octet);
                                message.Subject = "New Financial Request from " + username;
                                message.Body    = "Name:" + "\n" + username + "\n" + "\n" + "Time" + "\n" + dt + "\n" + "\n" + "Email:" + "\n" + email + "\n" + "\n" + "Phone:" + "\n" + phone + "\n" + "\n" + "Business Type:" + "\n" + "\n" + selected + "\n" + "\n" + "Turnover:" + "\n" + "\n" + turnover + "\n" + "\n" + "Number of Staff:" + "\n" + staffno + "\n" + "\n" + "Required Services:" + "\n" + "\n" + "Bookkeeping: " + bookkeeping
                                                  + "\n" + "Payroll: " + payroll + "\n" + "Companies House Returns: " + CompaniesHouseReturns + "\n" + "Self Assessment: " + SelfAssessment + "\n" +
                                                  "VAT Returns: " + VATReturns + "\n" + "Accounts Management: " + AccountsManagement + "\n" + "Business Consultation: " + BusinessConsultation + "\n" + "Taxation Advice: " + TaxationAdvice + "\n";


                                message.IsBodyHtml = false;

                                client.Credentials = new NetworkCredential(Utils.GetConfigSetting("Fredemail"), Utils.GetConfigSetting("fpw"));

                                // message.CC.Add(Utils.GetConfigSetting("Fredemail"));
                                // message.CC.Add(Utils.GetConfigSetting("Andrewemail"));
                                client.EnableSsl = true;
                                client.Send(message);

                                var document = new BsonDocument
                                {
                                    { "Name", (form1["name"].ToString()) },
                                    { "Email", (form1["email"].ToString()) },
                                    { "Phone", (form1["phone"].ToString()) },
                                    { "Staff Number", (form1["staffno"].ToString()) },
                                    { "Turnover", (form1["turnover"].ToString()) },
                                    { "Date", dt },
                                };

                                collec.InsertOneAsync(document);
                            }
                ViewBag.Message = "Email sent";
                return(View());
            }
            catch (Exception ex)
            {
                ViewBag.Message = "Email not sent" + "\n" + ex;
                return(View());
            }
        }
Beispiel #18
0
        private void simpleSend_Click(object sender, EventArgs e)
        {
            try
            {
                mail.From = new MailAddress(this.textUserMail.Text);
                client    = new SmtpClient();
                switch (mail.From.Host)
                {
                case "qq.com":
                    client.Host = "smtp.qq.com";
                    client.Port = 25;
                    break;

                case "126.com":
                    client.Host = "smtp.126.com";
                    client.Port = 25;
                    break;

                case "163.com":
                    client.Host = "smtp.163.com";
                    client.Port = 25;
                    break;

                case "gmail.com":
                    client.Host      = "smtp.gmail.com";
                    client.Port      = 587;
                    client.EnableSsl = true;
                    break;

                case "yahoo.com":
                    client.Host      = "smtp.yahoo.com";
                    client.Port      = 465;
                    client.EnableSsl = true;
                    break;

                default:
                    client.Host = "smtp.163.com";
                    client.Port = 25;
                    break;
                }
                client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                mail.Attachments.Clear();
                foreach (FileClass item in list)
                {
                    //FileInfo f = new FileInfo(item.filePath);
                    //string ext = f.Extension.ToLower();
                    System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType();
                    switch (item.Extension)
                    {
                    case ".rar":
                    case ".zip":
                        ct.MediaType = System.Net.Mime.MediaTypeNames.Application.Zip;
                        if (item.Desc == null || item.Desc == "")
                        {
                            ct.Name = item.fileName + item.Extension;
                        }
                        else
                        {
                            ct.Name = item.Desc + item.Extension;
                        }
                        mail.Attachments.Add(new Attachment(item.filePath, ct));
                        break;

                    default:
                        ct.MediaType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
                        if (item.Desc == null || item.Desc == "")
                        {
                            ct.Name = item.fileName + item.Extension;
                        }
                        else
                        {
                            ct.Name = item.Desc + item.Extension;
                        }
                        mail.Attachments.Add(new Attachment(item.filePath, ct));
                        break;
                    }
                }
                client.Credentials = new System.Net.NetworkCredential(this.textUserMail.Text, this.textUserPass.Text);
                client.Timeout     = int.MaxValue;
                mail.ReplyTo       = new MailAddress(this.textUserMail.Text);
                mail.IsBodyHtml    = true;
                mail.Sender        = new MailAddress(this.textUserMail.Text);
                mail.Priority      = MailPriority.High;
                mail.Subject       = this.textTitle.Text;
                mail.BodyEncoding  = System.Text.Encoding.UTF8;;
                mail.To.Add(this.textSupplierMail.Text);
                string bodystr = this.richContent.Text;
                bodystr         = bodystr.Replace("\n", "<br />");
                mail.Body       = bodystr;
                mail.IsBodyHtml = true;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                client.Send(mail);
                MessageBox.Show("郵件發送成功!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private Boolean sendMail(string StudetnName, string studentEmail, string msg)
        {
            try
            {
                {
                    System.Net.Mail.MailMessage message = new MailMessage("*****@*****.**", studentEmail);

                    // stdMailId = message.ToString();
                    StringBuilder str = new StringBuilder();

                    message.Subject = "Dheya Session completion OTP";
                    message.Body    = msg; // ConfigurationManager.AppSettings["assignSessionMail"].ToString();
                    message.Body    = message.Body.Replace("{StudetnName}", StudetnName);
                    //msg.Subject = txttitle.Text;
                    //msg.Body = txtdescription.Text;

                    string DateFormat = "yyyyMMddTHHmmssZ";
                    string now        = DateTime.Now.ToUniversalTime().ToString(DateFormat);

                    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}", DateTime.Parse("2019-12-25 20:00:00").ToUniversalTime()));
                    //str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", DateTime.Parse(SessionDt).ToUniversalTime()));

                    //str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.Now.ToUniversalTime().ToString(DateFormat)));
                    //str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", DateTime.Parse(SessionDt).ToUniversalTime()));


                    //str.AppendLine("LOCATION: " + txtlocation.Text);
                    str.AppendLine(string.Format("UID:{0}", Guid.NewGuid()));
                    str.AppendLine(string.Format("DESCRIPTION:{0}", message.Body));
                    str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", message.Body));
                    str.AppendLine(string.Format("SUMMARY:{0}", message.Subject));
                    str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", message.From.Address));

                    str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", message.To[0].DisplayName, message.To[0].Address));

                    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);

                    // Attachment attach = new Attachment(stream, "test.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);
                    message.AlternateViews.Add(avCal);

                    //Now sending a mail with attachment ICS file.
                    System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient();
                    smtpclient.Host = "smtp.gmail.com";
                    //smtpclient.Port = 587;
                    //-------this has to given the Mailserver IP
                    smtpclient.EnableSsl   = true;
                    smtpclient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "kglnnhvamtojscoa");
                    smtpclient.Send(message);

                    // Response.Write("Done");
                    return(true);
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                return(false);
            }
        }
Beispiel #20
0
        private MailMessage FormatoEvento(string status, List <string> receiverEmails, DateTime eventStart, DateTime eventEnd, string body, string subject, string location, Guid identifier, string from)
        {
            string method = "";

            switch (status)
            {
            case "REQUEST":
                method = "METHOD:REQUEST";
                break;

            case "CANCEL":
                method = "METHOD:CANCEL";
                break;

            default:
                method = "METHOD:REQUEST";
                break;
            }

            // Contruct the ICS file using string builder
            MailMessage m = new MailMessage();

            m.From = new MailAddress(from, "from");
            foreach (var to in receiverEmails)
            {
                m.To.Add(new MailAddress(to, to.Substring(0, to.IndexOf("@"))));
            }
            m.Subject = subject;
            m.Body    = body;
            StringBuilder str = new StringBuilder();

            str.AppendLine("BEGIN:VCALENDAR");
            str.AppendLine("PRODID:-//Schedule a Meeting");
            str.AppendLine("VERSION:2.0");
            str.AppendLine(method);
            str.AppendLine("BEGIN:VEVENT");
            str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", eventStart));
            str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
            str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", eventEnd));
            str.AppendLine("LOCATION: " + location);
            str.AppendLine(string.Format("UID:{0}", identifier));
            str.AppendLine(string.Format("DESCRIPTION:{0}", m.Body));
            str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", m.Body));
            str.AppendLine(string.Format("SUMMARY:{0}", m.Subject));
            str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", m.From.Address));

            for (int i = 0; i < m.To.Count; i++)
            {
                str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", m.To[i].DisplayName, m.To[i].Address));
            }

            str.AppendLine("BEGIN:VALARM");
            str.AppendLine("TRIGGER:-PT15M");
            str.AppendLine("ACTION:DISPLAY");
            str.AppendLine("DESCRIPTION:Reminder");
            str.AppendLine("END:VALARM");
            if (status == "CANCEL")
            {
                str.AppendLine("STATUS:CANCELLED");
            }
            str.AppendLine("END:VEVENT");
            str.AppendLine("END:VCALENDAR");

            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);

            m.AlternateViews.Add(avCal);

            return(m);
        }
Beispiel #21
0
        static System.Net.Mime.ContentType GetContentType(ContentType contentType)
        {
            var ctype = new System.Net.Mime.ContentType ();
            ctype.MediaType = string.Format ("{0}/{1}", contentType.MediaType, contentType.MediaSubtype);

            foreach (var param in contentType.Parameters)
                ctype.Parameters.Add (param.Name, param.Value);

            return ctype;
        }
Beispiel #22
0
 public AlternateView(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base(default(string))
 {
 }
Beispiel #23
0
 protected AttachmentBase(string fileName, System.Net.Mime.ContentType contentType)
 {
 }
        protected override void Execute(CodeActivityContext context)
        {
            ITracingService tracingService  = context.GetExtension <ITracingService>();
            var             workflowContext = context.GetExtension <IWorkflowContext>();
            var             serviceFactory  = context.GetExtension <IOrganizationServiceFactory>();
            var             orgService      = serviceFactory.CreateOrganizationService(workflowContext.UserId);
            DateTime        AcStartDate     = this.From.Get <DateTime>(context);
            DateTime        AcEndDate       = this.To.Get <DateTime>(context);
            string          _email          = this.Email.Get <string>(context);
            string          _subject        = this.Subject.Get <string>(context);
            string          _location       = this.Location.Get <string>(context);
            var             _isSSL          = this.IsEnableSSL.Get <bool>(context);
            //Get the Configuration
            EntityReference _config    = this.Configuration.Get <EntityReference>(context);
            var             ConfigData = orgService.Retrieve(_config.LogicalName, _config.Id, new ColumnSet(true));
            var             _smtpIP    = ConfigData.GetAttributeValue <string>("os_smtpip");
            var             _username  = ConfigData.GetAttributeValue <string>("os_username");
            var             _pass      = ConfigData.GetAttributeValue <string>("os_password");
            var             _sender    = ConfigData.GetAttributeValue <string>("emailaddress");
            var             _orgName   = ConfigData.GetAttributeValue <string>("os_name");
            var             _port      = ConfigData.GetAttributeValue <int>("os_port");
            IICalendar      iCal       = new iCalendar();

            iCal.Method = "Request";
            IEvent evt = iCal.Create <Event>();

            evt.Summary     = _subject;
            evt.Start       = new iCalDateTime(AcStartDate);
            evt.End         = new iCalDateTime(AcEndDate);
            evt.Description = _subject;
            evt.Location    = _location;
            tracingService.Trace("evt done");
            //evt.Name = _subject;
            //evt.Organizer = new Organizer("MAILTO:" + _sender);
            //evt.Organizer.CommonName = _orgName;
            Alarm alarm = new Alarm();

            // Display the alarm somewhere on the screen.
            alarm.Action = AlarmAction.Display;

            // This is the text that will be displayed for the alarm.
            alarm.Summary = _subject;

            // The alarm is set to occur 30 minutes before the event
            alarm.Trigger = new Trigger(TimeSpan.FromMinutes(-30));
            var serializer = new iCalendarSerializer(iCal);
            var iCalString = serializer.SerializeToString(iCal);
            var msg        = new MailMessage();

            msg.Subject = _subject;
            msg.Body    = _subject;
            msg.From    = new MailAddress(_sender);
            msg.To.Add(_email);

            tracingService.Trace("mail done");
            // Create the Alternate view object with Calendar MIME type
            var ct = new System.Net.Mime.ContentType("text/calendar");

            if (ct.Parameters != null)
            {
                ct.Parameters.Add("method", "REQUEST");
            }

            //Provide the framed string here
            AlternateView avCal = AlternateView.CreateAlternateViewFromString(iCalString, ct);

            msg.AlternateViews.Add(avCal);

            // Send email
            try
            {
                SendSMTP(_smtpIP, _port, _username, _pass, _isSSL);
                tracingService.Trace("done");
            }
            catch (Exception ex) { throw new InvalidPluginExecutionException("Error " + ex.Message); }
        }
Beispiel #25
0
 public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Net.Mime.ContentType contentType)
 {
     throw null;
 }
Beispiel #26
0
        private MailMessage CreateMailMessage(IEmail email)
        {
            var         data    = email.Data;
            MailMessage message = null;

            // Smtp seems to require the HTML version as the alternative.
            if (!string.IsNullOrEmpty(data.PlaintextAlternativeBody))
            {
                message = new MailMessage
                {
                    Subject    = data.Subject,
                    Body       = data.PlaintextAlternativeBody,
                    IsBodyHtml = false,
                    From       = new MailAddress(data.FromAddress.EmailAddress, data.FromAddress.Name)
                };

                var           mimeType  = new System.Net.Mime.ContentType("text/html; charset=UTF-8");
                AlternateView alternate = AlternateView.CreateAlternateViewFromString(data.Body, mimeType);
                message.AlternateViews.Add(alternate);
            }
            else
            {
                message = new MailMessage
                {
                    Subject         = data.Subject,
                    Body            = data.Body,
                    IsBodyHtml      = data.IsHtml,
                    BodyEncoding    = Encoding.UTF8,
                    SubjectEncoding = Encoding.UTF8,
                    From            = new MailAddress(data.FromAddress.EmailAddress, data.FromAddress.Name)
                };
            }

            data.ToAddresses.ForEach(x =>
            {
                message.To.Add(new MailAddress(x.EmailAddress, x.Name));
            });

            data.CcAddresses.ForEach(x =>
            {
                message.CC.Add(new MailAddress(x.EmailAddress, x.Name));
            });

            data.BccAddresses.ForEach(x =>
            {
                message.Bcc.Add(new MailAddress(x.EmailAddress, x.Name));
            });

            data.ReplyToAddresses.ForEach(x =>
            {
                message.ReplyToList.Add(new MailAddress(x.EmailAddress, x.Name));
            });

            switch (data.Priority)
            {
            case Priority.Low:
                message.Priority = MailPriority.Low;
                break;

            case Priority.Normal:
                message.Priority = MailPriority.Normal;
                break;

            case Priority.High:
                message.Priority = MailPriority.High;
                break;
            }

            data.Attachments.ForEach(x =>
            {
                message.Attachments.Add(new System.Net.Mail.Attachment(x.Data, x.Filename, x.ContentType));
            });

            return(message);
        }
        /// <summary>
        /// Checks whether a given content type is valid as a content type for resource data
        /// </summary>
        /// <param name="contentType">The content type, as it appears on e.g. a Http Content-Type header</param>
        /// <returns></returns>
        public static bool IsValidResourceContentType(string contentType)
        {
            var f = new System.Net.Mime.ContentType(contentType).MediaType.ToLowerInvariant();

            return JSON_CONTENT_HEADERS.Contains(f) || XML_CONTENT_HEADERS.Contains(f);
        }
Beispiel #28
0
        private bool EnvioFormulario(IDialogContext context, IAwaitable <IMessageActivity> messageActivity)
        {
            try
            {
                //Hotmail
                //SmtpClient SmtpServer = new SmtpClient("smtp.live.com");
                //Gmail
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                var        mail       = new MailMessage();
                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add("*****@*****.**");
                mail.Subject    = "Formulário crie seu bot";
                mail.IsBodyHtml = true;
                string htmlBody;
                htmlBody        = "Corpo da mensagem";
                mail.Body       = htmlBody;
                SmtpServer.Port = 587;
                SmtpServer.UseDefaultCredentials = false;
                //Hotmail
                //SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "senha do hotmail");
                //Gmail
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "panela123");
                SmtpServer.EnableSsl   = true;
                //SmtpServer.Send(mail);
                System.IO.MemoryStream ms     = new System.IO.MemoryStream();
                System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
                ms.Position = 0;
                //writer.Write(formularioFinal);

                System.Net.Mime.ContentType ct     = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
                System.Net.Mail.Attachment  attach = new System.Net.Mail.Attachment(ms, ct);
                attach.ContentDisposition.FileName = "formulario.json";

                //// I guess you know how to send email with an attachment
                //// after sending email
                mail.Attachments.Add(attach);
                //ms.Close();

                SmtpServer.Send(mail);
                ////context.Done(true);

                //try
                //{
                //    //Envia o email
                //    SmtpServer.Send(mail);
                //    return true;
                //}
                //catch (Exception e)
                //{
                //    return false;
                //    // erro eo enviar email
                //    //await context.PostAsync("erro eo enviar email");
                //    //await context.PostAsync("mensagem erro:" + e.Message);
                //}            }
                return(true);
            }
            catch (Exception e)

            {
                return(false);
            }
        }
        /// <summary>
        /// Handles events that occur after an action occurs, such as after a user adds an item to a list or deletes an item from a list.
        /// </summary>
        /// <param name="properties">Holds information about the remote event.</param>
        public void ProcessOneWayEvent(SPRemoteEventProperties properties)
        {
            using (ClientContext clientContext = TokenHelper.CreateRemoteEventReceiverClientContext(properties))
            {
                if (clientContext != null)
                {
                    //string Attendees = properties.ItemEventProperties.AfterProperties["ParticipantsPicker"].ToString();
                    List lstExternalEvents = clientContext.Web.Lists.GetByTitle(properties.ItemEventProperties.ListTitle);
                    ListItem itemEvent = lstExternalEvents.GetItemById(properties.ItemEventProperties.ListItemId);
                    clientContext.Load(itemEvent);
                    clientContext.ExecuteQuery();

                    clientContext.Load(clientContext.Web);
                    clientContext.ExecuteQuery();

                    string ItemURL = String.Empty;
                    List<Event> oList = new List<Event>();
                    Event oEvent = Event.Parse(itemEvent);
                    oEvent.Organizer = @"*****@*****.**";
                    oList.Add(oEvent);
                    string att = oEvent.ToString(oList);
                    
                    

                    List<string> tos = new List<string>();

                    string smtpserver = ConfigurationManager.AppSettings["smtpserver"].ToString();
                    string username = ConfigurationManager.AppSettings["username"].ToString();
                    string password = ConfigurationManager.AppSettings["password"].ToString();

                    SmtpClient mailserver = new SmtpClient(smtpserver, Convert.ToInt32(587));
                    mailserver.Credentials = new NetworkCredential(username, password);
                    MailAddress from = new MailAddress(@"*****@*****.**", "Shakir John");
                    MailMessage mess = new MailMessage();

                    try
                    {
                        FieldUserValue[] fTo = itemEvent["ParticipantsPicker"] as FieldUserValue[];
                        foreach (FieldUserValue fuv in fTo)
                        {
                            var userTo = clientContext.Web.EnsureUser(fuv.LookupValue);
                            clientContext.Load(userTo);
                            clientContext.ExecuteQuery();
                            tos.Add(userTo.Email);
                            mess.To.Add(new MailAddress(userTo.Email));
                        }
                        ItemURL = String.Empty;//itemEvent["URL"].ToString();
                    }
                    catch(Exception ex)
                    {

                    }

                    MemoryStream ms = new MemoryStream(GetData(att));
                    System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
                    System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
                    attach.ContentDisposition.FileName = "event.ics";

                    try
                    {
                        string subject = "ConnectORG Notification";
                        string body = String.Format(@"<html><body><h1>This is a ConnectORG Notification</h1><br>Please see your event <a href='{0}'>here</a></body></html>", ItemURL);
                        mess.From = from;
                        mess.Subject = subject;
                        mess.Body = body;
                        mess.IsBodyHtml = true;
                        mess.Attachments.Add(attach);
                        mailserver.Send(mess);
                    }
                    catch(SmtpException ex)
                    {

                    }
                    catch(Exception e)
                    {
                        
                    }

                    try
                    {
                        List AuditTrail = clientContext.Web.Lists.GetByTitle("Audit Trail");
                        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                        ListItem newItem = AuditTrail.AddItem(itemCreateInfo);
                        newItem["Title"] = String.Format("Sent Email to {0} people", tos.Count());
                        newItem["DateCompleted"] = DateTime.Now;
                        newItem.Update();
                        clientContext.ExecuteQuery();
                    }
                    catch
                    {

                    }
                  
                }
            }
        }
 public LinkedResource(string fileName, System.Net.Mime.ContentType contentType)
 {
 }
Beispiel #31
0
 public Attachment(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base(default(System.IO.Stream))
 {
 }
 public LinkedResource(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType)
 {
 }
Beispiel #33
0
        /// <summary>
        /// Sends the message, check Result property for success
        /// </summary>
        public void Send()
        {
            if (!IsValid())
            {
                return;
            }

            if (SenderName == "")
            {
                _mailMessage.From = new MailAddress(SenderAddress);
            }
            else
            {
                _mailMessage.From = new MailAddress(SenderAddress, SenderName);
            }

            string body = Body;

            if (UseHtml)
            {
                if (Body.IndexOf("<html") == -1)
                {
                    // add some HTML around the body
                    body = HTMLWrapper(Body);
                }

                System.Net.Mime.ContentType htmlType = new System.Net.Mime.ContentType("text/html");
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, htmlType);
                _mailMessage.AlternateViews.Add(htmlView);
            }

            string problem = string.Empty;


            _mailMessage.Body     = body;
            _mailMessage.Subject  = Subject;
            _mailMessage.Priority = MailPriority.Normal;

            if (Config.CurrentDebugLevel == Config.DebugLevels.Debug)
            {
                string debugFileName = "email";
                if (UseHtml)
                {
                    debugFileName += ".html";
                }
                else
                {
                    debugFileName += ".txt";
                }
                IOHelper.SaveDebugTextFile(debugFileName, this.ToString());
            }

            if (_smtpClient.Host == _noEmailHost)
            {
                // don't send any email
                return;
            }
            // we have a special host name, specified in
            // the config of unit testing
            // only if that's not set do we actually want to send the message
            try
            {
                _smtpClient.Send(_mailMessage);
            }
            catch (System.Net.Mail.SmtpException eSmtp)
            {
                if (LogExceptions)
                {
                    string innerExceptionMessage = string.Empty;
                    if (eSmtp.InnerException != null)
                    {
                        innerExceptionMessage = eSmtp.InnerException.Message;
                    }
                    Exceptions.Log(eSmtp, innerExceptionMessage + " " + this.ToString(), (int)Exceptions.LogTargets.File);
                }
                AddProblem("SmtpException: " + eSmtp.Message);
            }

            catch (Exception ex)
            {
                if (LogExceptions)
                {
                    Exceptions.Log(ex, this.ToString(), (int)Exceptions.LogTargets.File);
                }
                if (Config.CurrentDebugLevel > Config.DebugLevels.Stage)
                {
                    AddProblem("System Exception while sending email: " + ex.Message + " " + this.ToString());
                }
                else
                {
                    AddProblem("System Exception while sending email: " + ex.Message);
                }
            }
        }
 public static LinkedResource CreateLinkedResourceFromString(string content, System.Net.Mime.ContentType contentType)
 {
 }
Beispiel #35
0
 public static string FromMime(System.Net.Mime.ContentType value)
 {
     return(value.MediaType);
 }
Beispiel #36
0
 private System.Net.Mime.ContentType ToContentType(Rebex.Mime.Headers.ContentType rct)
 {
     System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(rct.MediaType);
     ct.MediaType = rct.MediaType;
     ct.Boundary = rct.Boundary;
     ct.CharSet = rct.CharSet;
     Rebex.Mime.Headers.MimeParameterList mpl = rct.Parameters;
     foreach (string name in mpl.Names)
     {
         ct.Parameters.Add(name, mpl[name]);
     }
     return ct;
 }
Beispiel #37
0
 public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, System.Net.Mime.ContentType contentType)
 {
     throw null;
 }
Beispiel #38
0
        /// <summary>
        /// Checks whether a given content type is valid as a content type for resource data
        /// </summary>
        /// <param name="contentType">The content type, as it appears on e.g. a Http Content-Type header</param>
        /// <returns></returns>
        public static bool IsValidResourceContentType(string contentType)
        {
            var f = new System.Net.Mime.ContentType(contentType).MediaType.ToLowerInvariant();

            return(JSON_CONTENT_HEADERS.Contains(f) || XML_CONTENT_HEADERS.Contains(f));
        }
Beispiel #39
0
 protected AttachmentBase(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType)
 {
 }
        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()));
            }
        }
Beispiel #41
0
 public LinkedResource(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base(default(string))
 {
 }
Beispiel #42
0
 public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Net.Mime.ContentType contentType)
 {
     throw null;
 }
Beispiel #43
0
 public AlternateView(string fileName, System.Net.Mime.ContentType contentType) : base(default(string))
 {
 }
Beispiel #44
0
        /// <summary>
        /// Send mail ICalendar
        /// </summary>
        /// <param name="mailMeetingEntity">MailMeetingEntity</param>
        /// <param name="actionBeforeSendMeeting">Action<MailMessage></param>
        public string SendMeeting(MailMeetingEntity mailMeetingEntity, Action <MailMessage> actionBeforeSendMeeting)
        {
            SmtpClient m_SmtpClient = new SmtpClient();

            if (this.MailConfig != null)
            {
                m_SmtpClient.UseDefaultCredentials = MailConfig.UseDefaultCredentials;
                if (!MailConfig.UseDefaultCredentials) //tạo mới Smtp Credentials
                {
                    m_SmtpClient.Credentials = new NetworkCredential(MailConfig.Username, MailConfig.Password, MailConfig.Domain);
                }
                m_SmtpClient.Port      = MailConfig.Port;
                m_SmtpClient.Host      = MailConfig.Host;
                m_SmtpClient.EnableSsl = MailConfig.EnableSsl;
            }

            MailMessage m_MailMessage = new MailMessage()
            {
                From       = new MailAddress(mailMeetingEntity.From),
                Body       = mailMeetingEntity.Body,
                Subject    = mailMeetingEntity.Subject,
                IsBodyHtml = true,
            };

            //Parse MailMeetingEntity -> ICalendar Entity

            // Create a new iCalendar
            iCalendar m_iCalendar = new iCalendar()
            {
                Method    = MailServiceICal.ICalendarMethod_Request, //PUBLISH THÌ KO ADD VÀO TRONG CALENDAR
                Version   = MailServiceICal.ICalendar_Version,
                ProductID = MailServiceICal.ICalendar_ProductID,
            };

            // Create the event, and add it to the iCalendar
            Event m_Event = m_iCalendar.Create <Event>();

            // Set information about the event
            m_Event.UID         = mailMeetingEntity.UID;
            m_Event.DTStamp     = new iCalDateTime(mailMeetingEntity.Stamp);
            m_Event.Start       = new iCalDateTime(mailMeetingEntity.Start);
            m_Event.End         = new iCalDateTime(mailMeetingEntity.End);
            m_Event.Description = mailMeetingEntity.Description;
            m_Event.Location    = mailMeetingEntity.Location;
            m_Event.Summary     = mailMeetingEntity.Description;
            //m_event.Transparency = TransparencyType.Opaque;

            //CONFIG ALARM
            foreach (var m_AlarmEntity in mailMeetingEntity.Alarms)
            {
                AlarmAction m_AlarmAction = new AlarmAction();
                if (m_AlarmEntity.Trigger.Equals(MailServiceICal.Action_Audio))
                {
                    m_AlarmAction = AlarmAction.Audio;
                }
                else if (m_AlarmEntity.Trigger.Equals(MailServiceICal.Action_Display))
                {
                    m_AlarmAction = AlarmAction.Display;
                }
                else if (m_AlarmEntity.Trigger.Equals(MailServiceICal.Action_Email))
                {
                    m_AlarmAction = AlarmAction.Email;
                }
                else if (m_AlarmEntity.Trigger.Equals(MailServiceICal.Action_Procedure))
                {
                    m_AlarmAction = AlarmAction.Procedure;
                }
                m_Event.Alarms.Add(new Alarm
                {
                    Duration    = m_AlarmEntity.Duration,
                    Trigger     = new Trigger(m_AlarmEntity.Trigger),
                    Description = m_AlarmEntity.Description,
                    Repeat      = m_AlarmEntity.RepeatTime,
                    Action      = m_AlarmAction,
                });
            }

            //Add Attendees
            var m_Attendes = new List <IAttendee>();

            foreach (var m_AttendeesEntity in mailMeetingEntity.Attendees)
            {
                m_MailMessage.To.Add(new MailAddress(m_AttendeesEntity.Email));
                IAttendee m_Attendee = new DDay.iCal.Attendee(MailServiceICal.Attendee_MailTo + m_AttendeesEntity.Email);
                if (m_AttendeesEntity.IsOptional)
                {
                    m_Attendee.Role = MailServiceICal.Role_Optional;
                }
                else
                {
                    m_Attendee.Role = MailServiceICal.Role_Request;
                }
                m_Attendes.Add(m_Attendee);
            }

            if (m_Attendes != null && m_Attendes.Count > 0)
            {
                m_Event.Attendees = m_Attendes;
            }

            //Check before send meeting
            if (actionBeforeSendMeeting != null)
            {
                actionBeforeSendMeeting(m_MailMessage);
            }

            DDay.iCal.Serialization.iCalendar.iCalendarSerializer m_Serializer = new DDay.iCal.Serialization.iCalendar.iCalendarSerializer();
            //Convert iCal to string
            string m_iCalendarData = m_Serializer.SerializeToString(m_iCalendar);

            System.Net.Mime.ContentType m_Contype = new System.Net.Mime.ContentType(MailServiceICal.ICalendar_ContentType);
            m_Contype.Parameters.Add(MailServiceICal.ICalendar_Method, MailServiceICal.ICalendarMethod_Request);
            m_Contype.Parameters.Add(MailServiceICal.ICalendar_Name, MailServiceICal.ICalendar_FileName);
            AlternateView m_AlternateView = AlternateView.CreateAlternateViewFromString(m_iCalendarData, m_Contype);

            m_MailMessage.AlternateViews.Add(m_AlternateView);

            m_SmtpClient.Send(m_MailMessage);
            return(m_iCalendarData);
        }
        public static void SendEmail(string from, string to, string cc, string bcc, string subject, string body, System.IO.Stream stream, string filename)
        {
            MailMessage EmailMsg = new MailMessage();
            EmailMsg.From = new MailAddress(from);
            EmailMsg.To.Add(new MailAddress(to));
            if (!cc.Trim().Equals(string.Empty))
            {
                EmailMsg.CC.Add(new MailAddress(cc));
            }
            if (!bcc.Trim().Equals(string.Empty))
            {
                EmailMsg.Bcc.Add(new MailAddress(bcc));
            }
            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);
        }
        private static Encoding getCharacterEncoding(HttpWebResponse response)
        {
            Encoding result = null;

            if (!String.IsNullOrEmpty(response.ContentType))
            {
#if PORTABLE45
				var charset = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(response.ContentType).CharSet;
#else
                var charset = new System.Net.Mime.ContentType(response.ContentType).CharSet;
#endif

                if (!String.IsNullOrEmpty(charset))
                    result = Encoding.GetEncoding(charset);
            }
            return result;
        }      
        /// <summary>
        /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream.
        /// </summary>
        /// <param name="request">The WebRequest who's content is to be set</param>
        /// <param name="content">A String object containing the content data.</param>
        /// <returns>The number of bytes written to the requests RequestStream (and the new value of the request's ContentLength property</returns>
        /// <remarks>
        /// Because this function sets the request's ContentLength property and writes content data into the requests's stream,
        /// it should be called one time maximum on a given request.
        /// </remarks>
        internal long SetRequestContent(WebRequest request, String content)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            if (content != null)
            {
                Encoding encoding = null;
                if (null != ContentType)
                {
                    // If Content-Type contains the encoding format (as CharSet), use this encoding format 
                    // to encode the Body of the WebRequest sent to the server. Default Encoding format 
                    // would be used if Charset is not supplied in the Content-Type property.
                    System.Net.Mime.ContentType mimeContentType = new System.Net.Mime.ContentType(ContentType);
                    if (!String.IsNullOrEmpty(mimeContentType.CharSet))
                    {
                        try
                        {
                            encoding = Encoding.GetEncoding(mimeContentType.CharSet);
                        }
                        catch (ArgumentException ex)
                        {
                            ErrorRecord er = new ErrorRecord(ex, "WebCmdletEncodingException", ErrorCategory.InvalidArgument, ContentType);
                            ThrowTerminatingError(er);
                        }
                    }
                }

                Byte[] bytes = StreamHelper.EncodeToBytes(content, encoding);

                if (request.ContentLength == 0)
                {
                    request.ContentLength = bytes.Length;
                }
                StreamHelper.WriteToStream(bytes, request.GetRequestStream());
            }
            else
            {
                request.ContentLength = 0;
            }

            return request.ContentLength;
        }
Beispiel #48
0
 /// <summary>
 ///   Creates an instance of the AlternateView class used by the MailMessage class
 ///   to store alternate views of the mail message's content.
 /// </summary>
 /// <param name="part">The MIME body part to create the alternate view from.</param>
 /// <param name="bytes">
 ///   An array of bytes composing the content of the
 ///   alternate view
 /// </param>
 /// <returns>An initialized instance of the AlternateView class</returns>
 private static AlternateView CreateAlternateView(Bodypart part, byte[] bytes)
 {
   var stream = new MemoryStream(bytes);
   System.Net.Mime.ContentType contentType;
   try
   {
     contentType = new System.Net.Mime.ContentType(
       part.Type.ToString().ToLower() + "/" + part.Subtype.ToLower());
   }
   catch
   {
     contentType = new System.Net.Mime.ContentType();
   }
   var view = new AlternateView(stream, contentType);
   try
   {
     view.ContentId = ParseMessageId(part.Id);
   }
   catch
   {
   }
   return view;
 }
Beispiel #49
0
        public async Task<IActionResult> ExportToCsvAndMail()
        {
            var user = await _userManager.FindByIdAsync(User.GetUserId());
            var admins = await _userManager.GetUsersInRoleAsync(AppRole.AdminsRole);
            var exportResult = await _customersManager.GetCustomersCSV();
            if (exportResult.Succeeded)
            {
                try
                {
                    var memStream = new MemoryStream(Encoding.UTF8.GetBytes(exportResult.Item.ToString()));                    
                    memStream.Position = 0;
                    var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
                    var reportAttachment = new System.Net.Mail.Attachment(memStream, contentType);
                    reportAttachment.ContentDisposition.FileName = "clients.csv";
                    
                    await NotificationManager.SendAsync(user.Email,
                                    admins.Select(u => u.Email).Where(e => !string.IsNullOrEmpty(e)).ToArray(),
                                    "Customers CSV",
                                    "Customers CSV",
                                    reportAttachment);

                    return new ObjectResult(new { OK = true });
                }
                catch (Exception ex)
                {
                    NotificationManager.SendErrorMessage(ex);
                    return HttpBadRequest(ex);
                }
            }
            return HttpBadRequest();
        }
        /// <summary>
        /// Sends a cancellation to the people specified
        /// </summary>
        public virtual void SendCancelEmails()
        {
            using (MailMessage Mail = new MailMessage())
            {
                System.Net.Mime.ContentType TextType = new System.Net.Mime.ContentType("text/plain");
                using (AlternateView TextView = AlternateView.CreateAlternateViewFromString(GetText(), TextType))
                {
                    System.Net.Mime.ContentType HTMLType = new System.Net.Mime.ContentType("text/html");
                    using (AlternateView HTMLView = AlternateView.CreateAlternateViewFromString(GetHTML(true), HTMLType))
                    {
                        System.Net.Mime.ContentType CalendarType = new System.Net.Mime.ContentType("text/calendar");
                        CalendarType.Parameters.Add("method", "CANCEL");
                        CalendarType.Parameters.Add("name", "meeting.ics");
                        using (AlternateView CalendarView = AlternateView.CreateAlternateViewFromString(GetCalendar(true), CalendarType))
                        {
                            CalendarView.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;

                            Mail.AlternateViews.Add(TextView);
                            Mail.AlternateViews.Add(HTMLView);
                            Mail.AlternateViews.Add(CalendarView);

                            Mail.From = new MailAddress(OrganizerEmail);
                            foreach (MailAddress attendee in AttendeeList)
                            {
                                Mail.To.Add(attendee);
                            }
                            Mail.Subject = Subject + " - Cancelled";
                            foreach (Attachment Attachment in Attachments)
                            {
                                Mail.Attachments.Add(Attachment);
                            }
                            SmtpClient Server = new SmtpClient(ServerName, Port);
                            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
                            {
                                Server.Credentials = new System.Net.NetworkCredential(UserName, Password);
                            }
                            if (AttendeeList.Count > 0)
                            {
                                Server.Send(Mail);
                            }
                        }
                    }
                }
            }
        }
        private void fn_envioCorreoAutomatizado(string strMsgErr)
        {
            try
            {
                char[] cCut = { ',', ';', ':', '-', ' ' };
                string[] strPara = Properties.Settings.Default.strCuentaReceptora.ToString().Split(cCut);

                foreach (string strDato in strPara)
                {
                    string strMssg =
                          "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"
                        + "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">"
                        + "</HEAD>"
                        + "<BODY>"
                            + "<table align = 'center' width = 1200>"
                                + "<tr><td><font size = '3' face = 'Calibri'>Buen D&iacute;a,</font> " + strDato + " </td>"
                                + "<td align = 'right'><font size = '2' face = 'Calibri'>" + DateTime.Now.ToString("D") + "</font></td></tr>"
                            + "</table>"
                            + "<p><font size = '3' face = 'Calibri'>"
                                + "Por medio de la presente, se notifica que se ha perdido la conexion con el servidor de mysql, "
                                + "<br>y por consiguiente el daemon volcador ha sido detenido. " + DateTime.Now.ToString() + ".</br>"
                                + "<br> </br>"
                                + "<br> Mensaje del error: </br>"
                                + "<br>" + strMsgErr + "</br>"
                            + "</font></p>"
                            + "<p><font size = '3' face = 'Calibri'>"
                                + "[Daemon Ikor]."
                            + "</font></p>"
                            + "<p><font size = '1' face = 'Calibri'>"
                                + "<hr color = #E46C0A>"
                                + "Correo generado autom&aacute;ticamente desde el [Daemon Ikor]."
                            + "</font></p>"
                        + "</BODY>";

                    MailMessage message = new MailMessage();
                    MailAddress fromAddress = new MailAddress(Properties.Settings.Default.strCuentaEmisora);
                    MailAddress toAddress = new MailAddress(strDato, "");
                    message.From = fromAddress;
                    message.To.Add(toAddress);
                    message.Subject = "Daemon Ikor - Volcador Detenido";
                    message.Body = strMssg;
                    System.Net.Mime.ContentType mType = new System.Net.Mime.ContentType("text/html");
                    System.Net.Mail.AlternateView mView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(strMssg, mType);
                    message.AlternateViews.Add(mView);
                    message.Priority = System.Net.Mail.MailPriority.High;
                    SmtpClient smtpClient = new SmtpClient();
                    smtpClient.Host = "smtp.gmail.com";
                    smtpClient.Port = 587;
                    smtpClient.Credentials = new System.Net.NetworkCredential(Properties.Settings.Default.strCuentaEmisora, Properties.Settings.Default.strContrasenaEmisora);
                    smtpClient.EnableSsl = true;
                    smtpClient.Send(message);
                }

            }
            catch
            {
            }
        }
Beispiel #52
0
 public void AddMeetingRequestToMsg(MailMessage msg, FiledDocInfo fdi)
 {
     StringBuilder str = new StringBuilder();
     str.AppendLine("BEGIN:VCALENDAR");
     str.AppendLine("VERSION:2.0");
     str.AppendLine("METHOD:REQUEST");
     str.AppendLine("BEGIN:VEVENT");
     str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", fdi.filedAs_eventDateTime));
     str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", fdi.filedAs_eventDateTime.ToUniversalTime()));
     str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", fdi.filedAs_eventDateTime.Add(fdi.filedAs_eventDuration)));
     str.AppendLine(string.Format("LOCATION: {0}", fdi.filedAs_eventLocation));
     str.AppendLine(string.Format("UID:{0}", Guid.NewGuid()));
     str.AppendLine(string.Format("DESCRIPTION:{0}", fdi.filedAs_eventDescr));
     str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", fdi.filedAs_eventDescr));
     str.AppendLine(string.Format("SUMMARY:{0}", fdi.filedAs_eventName));
     str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", msg.From.Address));
     foreach (MailAddress emto in msg.To)
         str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", emto.DisplayName, emto.Address));
     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");
     System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
     ct.Parameters.Add("method", "REQUEST");
     AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), ct);
     msg.AlternateViews.Add(avCal);
 }
 public static Encoding ExtractEncoding(string contentType, Encoding fallback)
 {
     if (string.IsNullOrEmpty(contentType))
     {
         return fallback;
     }
     var mime = new System.Net.Mime.ContentType(contentType);
     var cs = mime.Parameters["charset"];
     return string.IsNullOrEmpty(cs) ? fallback : Encoding.GetEncoding(cs);
 }
        public bool SendMail()
        {
            try
            {
                var sc = new SmtpClient("smtp.gmail.com")
                    {
                        Port = 587,
                        Credentials = new System.Net.NetworkCredential("username", "password"),
                        EnableSsl = true
                    };

                var msg = new MailMessage {From = new MailAddress("*****@*****.**", "System")};
                foreach (MailAddressObject obj in Mail)
                {
                    msg.To.Add(new MailAddress(obj.Email, obj.Name));
                }
                msg.Subject = Subject;
                msg.Body = Body;

                var iCal = new iCalendar {Method = "REQUEST"};

                // Create the event
                var evt = iCal.Create<Event>();

                evt.Summary = Summary;
                evt.Start = new iCalDateTime(StartTime.Year, StartTime.Month, StartTime.Day, StartTime.Hour, StartTime.Minute, StartTime.Second);
                evt.End = new iCalDateTime(EndTime.Year, EndTime.Month, EndTime.Day, EndTime.Hour, EndTime.Minute, EndTime.Second);
                evt.Description = Description;
                evt.Location = Location;

                //evt.Organizer = new Organizer("Phats");
                var alarm = new Alarm
                    {
                        Action = AlarmAction.Display,
                        Summary = AlarmSummary,
                        Trigger =
                            new Trigger(TimeSpan.FromMinutes(0 - ServiceFacade.SettingsHelper.TimeLeftRemindAppointment))
                    };
                evt.Alarms.Add(alarm);

                var serializer = new iCalendarSerializer(iCal);
                string icalData = serializer.SerializeToString(serializer);

                // Set up the different mime types contained in the message
                var loTextType = new System.Net.Mime.ContentType("text/plain");
                var loHtmlType = new System.Net.Mime.ContentType("text/html");
                var loCalendarType = new System.Net.Mime.ContentType("text/calendar");

                // Add parameters to the calendar header
                if (loCalendarType.Parameters != null)
                {
                    loCalendarType.Parameters.Add("method", "REQUEST");
                    loCalendarType.Parameters.Add("name", "meeting.ics");
                }

                AlternateView loTextView = AlternateView.CreateAlternateViewFromString(icalData, loTextType);
                msg.AlternateViews.Add(loTextView);

                AlternateView loHtmlView = AlternateView.CreateAlternateViewFromString(icalData, loHtmlType);
                msg.AlternateViews.Add(loHtmlView);

                AlternateView loCalendarView = AlternateView.CreateAlternateViewFromString(icalData, loCalendarType);
                loCalendarView.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
                msg.AlternateViews.Add(loCalendarView);

                sc.Send(msg);
                return true;
            }
            catch (Exception ex)
            {
                //SingletonLogger.Instance.Error("MailAppointment.SendMail", ex);
                return false;
            }
        }
Beispiel #55
0
 public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, System.Net.Mime.ContentType contentType)
 {
     return(default(System.Net.Mail.Attachment));
 }
Beispiel #56
0
 public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Net.Mime.ContentType contentType)
 {
     return(default(System.Net.Mail.LinkedResource));
 }
Beispiel #57
0
        //private void AjustarCodigosDeReferenciaEnFooter()
        //{
        //    referenciasGridView.DataBind();
        //    ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataValueField = "Codigo";
        //    ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataTextField = "Descr";
        //    if (Funciones.SessionTimeOut(Session))
        //    {
        //        Response.Redirect("~/SessionTimeout.aspx");
        //    }
        //    else
        //    {
        //        if (((Entidades.Sesion)Session["Sesion"]).Usuario != null)
        //        {
        //            //if (!Punto_VentaTextBox.Text.Equals(string.Empty))
        //            if (!PuntoVtaDropDownList.SelectedValue.Equals(string.Empty))
        //            {
        //                int auxPV;
        //                try
        //                {
        //                    auxPV = Convert.ToInt32(PuntoVtaDropDownList.SelectedValue);
        //                    string idtipo = ((Entidades.Sesion)Session["Sesion"]).UN.PuntosVta.Find(delegate(Entidades.PuntoVta pv)
        //                    {
        //                        return pv.Nro == auxPV;
        //                    }).IdTipoPuntoVta;
        //                    switch (idtipo)
        //                    {
        //                        case "Comun":
        //                        case "RG2904":
        //                        case "BonoFiscal":
        //                            ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataSource = FeaEntidades.CodigosReferencia.CodigoReferencia.Lista();
        //                            ((AjaxControlToolkit.MaskedEditExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoMaskedEditExtender")).Enabled = false;
        //                            ((AjaxControlToolkit.FilteredTextBoxExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoFilteredTextBoxExtender")).Enabled = true;
        //                            break;
        //                        case "Exportacion":
        //                            ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataSource = FeaEntidades.CodigosReferencia.Exportaciones.Exportacion.Lista();
        //                            ((AjaxControlToolkit.MaskedEditExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoMaskedEditExtender")).Enabled = true;
        //                            ((AjaxControlToolkit.FilteredTextBoxExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoFilteredTextBoxExtender")).Enabled = false;
        //                            break;
        //                        default:
        //                            throw new Exception("Tipo de punto de venta no contemplado en la lógica de la aplicación (" + idtipo + ")");
        //                    }
        //                }
        //                catch
        //                {
        //                    ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataSource = FeaEntidades.CodigosReferencia.CodigoReferencia.Lista();
        //                    ((AjaxControlToolkit.MaskedEditExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoMaskedEditExtender")).Enabled = false;
        //                    ((AjaxControlToolkit.FilteredTextBoxExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoFilteredTextBoxExtender")).Enabled = true;
        //                }
        //            }
        //            else
        //            {
        //                ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataSource = FeaEntidades.CodigosReferencia.CodigoReferencia.Lista();
        //                ((AjaxControlToolkit.MaskedEditExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoMaskedEditExtender")).Enabled = false;
        //                ((AjaxControlToolkit.FilteredTextBoxExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoFilteredTextBoxExtender")).Enabled = true;
        //            }
        //        }
        //        else
        //        {
        //            ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataSource = FeaEntidades.CodigosReferencia.CodigoReferencia.Lista();
        //            ((AjaxControlToolkit.MaskedEditExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoMaskedEditExtender")).Enabled = false;
        //            ((AjaxControlToolkit.FilteredTextBoxExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoFilteredTextBoxExtender")).Enabled = true;
        //        }
        //        ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataBind();
        //    }
        //}
        protected void AccionObtenerXMLButton_Click(object sender, EventArgs e)
        {
            if (Funciones.SessionTimeOut(Session))
            {
                Response.Redirect("~/SessionTimeout.aspx");
            }
            else
            {
                ActualizarEstadoPanel.Visible = false;
                DescargarPDFPanel.Visible = false;
                //ActualizarEstadoButton.DataBind();
                //DescargarPDFButton.DataBind();
                if (((Entidades.Sesion)Session["Sesion"]).Usuario.Id == null)
                {
                    ScriptManager.RegisterClientScriptBlock(this, GetType(), "Message", Funciones.TextoScript("Su sesión ha caducado por inactividad. Por favor vuelva a loguearse."), false);
                }
                else
                {
                    try
                    {
                        if (ValidarCamposObligatorios("ObtenerXML"))
                        {
                            //Generar Lote
                            FeaEntidades.InterFacturas.lote_comprobantes lote = GenerarLote(false);

                            //Grabar en base de datos
                            lote.cabecera_lote.DestinoComprobante = "ITF";
                            lote.comprobante[0].cabecera.informacion_comprobante.Observacion = "";

                            //Registrar comprobante si no es el usuario de DEMO.
                            Entidades.Sesion sesion = (Entidades.Sesion)Session["Sesion"];
                            if (sesion.UsuarioDemo != true)
                            {
                                Entidades.Comprobante cAux = new Entidades.Comprobante();
                                cAux.Cuit = lote.cabecera_lote.cuit_vendedor.ToString();
                                cAux.TipoComprobante.Id = lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante;
                                cAux.NroPuntoVta = lote.comprobante[0].cabecera.informacion_comprobante.punto_de_venta;
                                cAux.Nro = lote.comprobante[0].cabecera.informacion_comprobante.numero_comprobante;
                                RN.Comprobante.Leer(cAux, sesion);
                                if (cAux.Estado == null || cAux.Estado != "Vigente")
                                {
                                    RN.Comprobante.Registrar(lote, null, IdNaturalezaComprobanteTextBox.Text, "ITF", "PteEnvio", PeriodicidadEmisionDropDownList.SelectedValue, DateTime.ParseExact(FechaProximaEmisionDatePickerWebUserControl.Text, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture), Convert.ToInt32(CantidadComprobantesAEmitirTextBox.Text), Convert.ToInt32(CantidadComprobantesEmitidosTextBox.Text), Convert.ToInt32(CantidadDiasFechaVtoTextBox.Text), string.Empty, false, string.Empty, string.Empty, string.Empty, ((Entidades.Sesion)Session["Sesion"]));
                                }
                            }

                            AjustarLoteParaITF(lote);

                            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(lote.GetType());
                            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                            sb.Append(lote.cabecera_lote.cuit_vendedor);
                            sb.Append("-");
                            sb.Append(lote.cabecera_lote.punto_de_venta.ToString("0000"));
                            sb.Append("-");
                            sb.Append(lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante.ToString("00"));
                            sb.Append("-");
                            sb.Append(lote.comprobante[0].cabecera.informacion_comprobante.numero_comprobante.ToString("00000000"));
                            sb.Append(".xml");

                            System.IO.MemoryStream m = new System.IO.MemoryStream();
                            System.IO.StreamWriter sw = new System.IO.StreamWriter(m);
                            sw.Flush();
                            System.Xml.XmlWriter writerdememoria = new System.Xml.XmlTextWriter(m, System.Text.Encoding.GetEncoding("ISO-8859-1"));
                            x.Serialize(writerdememoria, lote);
                            m.Seek(0, System.IO.SeekOrigin.Begin);

                            string smtpXAmb = System.Configuration.ConfigurationManager.AppSettings["Ambiente"].ToString();
                            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

                            try
                            {
                                RegistrarActividad(lote, sb, smtpClient, smtpXAmb, m);
                            }
                            catch
                            {
                            }

                            if (((Button)sender).ID == "DescargarXMLButton")
                            {
                                //Descarga directa del XML
                                System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(@"~/Temp/" + sb.ToString()), System.IO.FileMode.Create);
                                m.WriteTo(fs);
                                fs.Close();
                                Server.Transfer("~/DescargaTemporarios.aspx?archivo=" + sb.ToString(), false);
                            }
                            else
                            {
                                //Envio por mail del XML
                                System.Net.Mail.MailMessage mail;
                                if (((Entidades.Sesion)Session["Sesion"]).Usuario.Id != null)
                                {
                                    mail = new System.Net.Mail.MailMessage("*****@*****.**",
                                        ((Entidades.Sesion)Session["Sesion"]).Usuario.Email,
                                        "Ced-eFact-Envío automático archivo XML:" + sb.ToString()
                                        , string.Empty);
                                }
                                else
                                {
                                    mail = new System.Net.Mail.MailMessage("*****@*****.**",
                                        Email_VendedorTextBox.Text,
                                        "Ced-eFact-Envío automático archivo XML:" + sb.ToString()
                                        , string.Empty);
                                }
                                System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
                                contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;
                                contentType.Name = sb.ToString();
                                System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(m, contentType);
                                mail.Attachments.Add(attachment);
                                mail.BodyEncoding = System.Text.Encoding.UTF8;
                                mail.Body = Mails.Body.AgregarBody();
                                smtpClient.Host = "localhost";
                                if (smtpXAmb.Equals("DESA"))
                                {
                                    string MailServidorSmtp = System.Configuration.ConfigurationManager.AppSettings["MailServidorSmtp"];
                                    if (MailServidorSmtp != "")
                                    {
                                        string MailCredencialesUsr = System.Configuration.ConfigurationManager.AppSettings["MailCredencialesUsr"];
                                        string MailCredencialesPsw = System.Configuration.ConfigurationManager.AppSettings["MailCredencialesPsw"];
                                        smtpClient.Host = MailServidorSmtp;
                                        if (MailCredencialesUsr != "")
                                        {
                                            smtpClient.Credentials = new System.Net.NetworkCredential(MailCredencialesUsr, MailCredencialesPsw);
                                        }
                                        smtpClient.Credentials = new System.Net.NetworkCredential(MailCredencialesUsr, MailCredencialesPsw);
                                    }
                                }
                                smtpClient.Send(mail);
                            }
                            m.Close();

                            if (!smtpXAmb.Equals("DESA"))
                            {
                                ScriptManager.RegisterClientScriptBlock(this, GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Archivo enviado satisfactoriamente');window.open('https://srv1.interfacturas.com.ar/cfeWeb/faces/login/identificacion.jsp/', '_blank');</script>", false);
                            }
                            else
                            {
                                ScriptManager.RegisterClientScriptBlock(this, GetType(), "Message", Funciones.TextoScript("Archivo enviado satisfactoriamente"), false);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ScriptManager.RegisterClientScriptBlock(this, GetType(), "Message", Funciones.TextoScript("Problemas al generar el archivo.  " + ex.Message), false);
                    }
                }
            }
        }
Beispiel #58
0
 public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Net.Mime.ContentType contentType)
 {
     return(default(System.Net.Mail.AlternateView));
 }
 /// <summary>
 /// Sends an email
 /// </summary>
 /// <param name="MessageBody">The body of the message</param>
 public override void SendMail(string MessageBody = "")
 {
     using (MailMessage Mail = new MailMessage())
     {
         using (AlternateView TextView = AlternateView.CreateAlternateViewFromString(AppointmentInfo.ToString(), new System.Net.Mime.ContentType("text/plain")))
         {
             using (AlternateView HTMLView = AlternateView.CreateAlternateViewFromString(AppointmentInfo.GetHCalendar(), new System.Net.Mime.ContentType("text/html")))
             {
                 System.Net.Mime.ContentType CalendarType = new System.Net.Mime.ContentType("text/calendar");
                 CalendarType.Parameters.Add("method", AppointmentInfo.Cancel ? "CANCEL" : "REQUEST");
                 CalendarType.Parameters.Add("name", "meeting.ics");
                 using (AlternateView CalendarView = AlternateView.CreateAlternateViewFromString(AppointmentInfo.GetICalendar(), CalendarType))
                 {
                     CalendarView.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
                     Mail.AlternateViews.Add(TextView);
                     Mail.AlternateViews.Add(HTMLView);
                     Mail.AlternateViews.Add(CalendarView);
                     char[] Splitter = { ',', ';' };
                     string[] AddressCollection = To.Split(Splitter);
                     for (int x = 0; x < AddressCollection.Length; ++x)
                     {
                         if (!string.IsNullOrEmpty(AddressCollection[x].Trim()))
                             Mail.To.Add(AddressCollection[x]);
                     }
                     if (!string.IsNullOrEmpty(CC))
                     {
                         AddressCollection = CC.Split(Splitter);
                         for (int x = 0; x < AddressCollection.Length; ++x)
                         {
                             if (!string.IsNullOrEmpty(AddressCollection[x].Trim()))
                                 Mail.CC.Add(AddressCollection[x]);
                         }
                     }
                     if (!string.IsNullOrEmpty(Bcc))
                     {
                         AddressCollection = Bcc.Split(Splitter);
                         for (int x = 0; x < AddressCollection.Length; ++x)
                         {
                             if (!string.IsNullOrEmpty(AddressCollection[x].Trim()))
                                 Mail.Bcc.Add(AddressCollection[x]);
                         }
                     }
                     Mail.From = new MailAddress(From);
                     Mail.Subject = Subject;
                     foreach (Attachment Attachment in Attachments)
                     {
                         Mail.Attachments.Add(Attachment);
                     }
                     if (Attachments.Count > 0)
                         Mail.Attachments.Add(new Attachment(new MemoryStream(AppointmentInfo.GetICalendar().ToByteArray()), "meeting.ics"));
                     Mail.Priority = Priority;
                     Mail.SubjectEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
                     Mail.BodyEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
                     using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(Server, Port))
                     {
                         if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
                         {
                             smtp.Credentials = new System.Net.NetworkCredential(UserName, Password);
                         }
                         if (UseSSL)
                             smtp.EnableSsl = true;
                         else
                             smtp.EnableSsl = false;
                         smtp.Send(Mail);
                     }
                 }
             }
         }
     }
 }
Beispiel #60
0
        public void SendMail(string[] args)
        {
            int cnt = -1;

            if (String.IsNullOrEmpty(_smtpAdress))
                return;

            Log("START process");
            if (mEvt.WaitOne(5000, false) == false)
            {

            }
            mEvt.Reset();

            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Usage: | SendMailAttach | Subject | Body | To | Attachment_FileName ");
                    return;
                }

                //using (System.IO.StreamWriter wrt =
                //    new System.IO.StreamWriter("c:\\sendmail.log", true))
                //{
                try
                {
                    string newTempStr = String.Join(" ", args);
                    //string[] newArgs = newTempStr.Split('|');
                    Log(newTempStr);
                    string[] adress = args[3].Split(';');
                    Log(adress[0].Trim());
                    if (!string.IsNullOrEmpty(adress[0].Trim()))
                    {
                        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                        if (_sendCopyToSender)
                            message.To.Add(new MailAddress(_From, _nameFrom));
                        
                        message.From = new MailAddress(_From, _nameFrom);
                        message.IsBodyHtml = false;

                        message.BodyEncoding = Encoding.GetEncoding("KOI8-R");
                        //message.AlternateViews.Add(new AlternateView(

                        Log(args[1].Replace("\r\n", " ").Trim());
                        message.Subject = args[1].Replace("\r\n", " ").Trim();

                        for (int i = 0; i < adress.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(adress[i].Trim()))
                            {
                                Log(adress[i].Trim());
                                message.Bcc.Add(adress[i].Trim());
                                //message.Bcc.Add("*****@*****.**");
                                //message.Bcc.Add("*****@*****.**");

                            }
                        }
                        //SmtpClient client = new SmtpClient("exchange.ramenka.ru");
                        SmtpClient client = new SmtpClient(_smtpAdress);
                        client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;


                        message.Body = args[2].Trim();
                        Log(args[2].Trim());


                        if (args.Length >= 5 && (!String.IsNullOrEmpty(args[4].Trim())))
                        {
                            Log(args[4].Trim());
                            System.Net.Mime.ContentType cType = new System.Net.Mime.ContentType("application/vnd.ms-excel");
                            cType.Name = System.IO.Path.GetFileName(args[4].Trim());
                            Attachment data = new Attachment(args[4].Trim(), cType);
                            System.Net.Mime.ContentDisposition disposition = data.ContentDisposition;
                            disposition.FileName = cType.Name;
                            disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;


                            message.Attachments.Add(data);

                        }

                        try
                        {
                            client.Send(message);
                            Log("Mail succesully sended to " + args[3]);
                        }
                        catch (Exception err)
                        {
                            Log(err.ToString());

                        }
                    }
                }
                catch (Exception err)
                {
                    Log(err.ToString());

                }
                finally
                {

                    //wrt.Flush();
                    //wrt.Close();
                }
                // }

            }
            catch { }

            finally
            {
                mEvt.Set();
                //   mut.ReleaseMutex();
                Log("END process");
            }

        }