/// <summary> /// Forward the selected email as an attachment /// </summary> private void SendMailAsAttachment() { if (!String.IsNullOrEmpty(email)) { Outlook.MailItem selectedMail = GetSelectedItem(); if (selectedMail != null) { var olapp = new Microsoft.Office.Interop.Outlook.Application(); Outlook.MailItem mail = olapp.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem; mail.Subject = "ForwardIt"; //Add the configured email. mail.Recipients.Add(email); mail.Attachments.Add(selectedMail, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing); mail.Send(); } else { MessageBox.Show("No items selected..."); } } else { MessageBox.Show("Email isn't configured"); } }
public AddMission(Mission m) { InitializeComponent(); Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 100, 100)); dateTimePicker_dueDate.Value = DateTime.Now.AddDays(7); this.updateMission = true; Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace ns = app.GetNamespace("MAPI"); Outlook.MAPIFolder f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox); foreach (string reci in m.Recipients) { listBox_Recipients.Items.Add(reci); } this.currentMission = m; textBox_Sbuject.Text = m.Title; richTextBox_Body.Text = m.Body; dateTimePicker_dueDate.Value = m.DueDate; this.orginizer = app.Session.CurrentUser.Name; label_Title.Text = "עדכן משימה"; button_Add.Text = "עדכן"; EnableButtonsInUpdate(m.Orginizer); }
private void FindContactEmailByName(string firstName, string lastName) { Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace outlookNameSpace = app.GetNamespace("MAPI"); Outlook.MAPIFolder f = outlookNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderInbox); Outlook.MAPIFolder contactsFolder = outlookNameSpace.GetDefaultFolder( Microsoft.Office.Interop.Outlook. OlDefaultFolders.olFolderContacts); Outlook.Items contactItems = contactsFolder.Items; try { Outlook.ContactItem contact = (Outlook.ContactItem)contactItems. Find(String.Format("[FirstName]='{0}' and " + "[LastName]='{1}'", firstName, lastName)); if (contact != null) { // return contact; contact.Display(true); } else { MessageBox.Show("The contact information was not found."); } } catch (System.Exception ex) { throw ex; } }
public Form_Main() { InitializeComponent(); dateTimePicker_MaxDateMissions.Value = DateTime.Now.AddMonths(1); dateTimePicker_MinDate.Value = DateTime.Now.AddDays(-4); dateTimePicker_MinDate.ValueChanged += dateTimePicker_MinDate_ValueChanged; dateTimePicker_MaxDateMissions.ValueChanged += dateTimePicker_MaxDateMissions_ValueChanged; Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace ns = app.GetNamespace("MAPI"); Outlook.MAPIFolder f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox); // Thread.Sleep(5000); // Microsoft.Office.Interop.Outlook.MailItem mailItem = (Outlook.MailItem)app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); toolStripStatusLabel_Name.Text = "חובר כ: " + app.Session.CurrentUser.Name; LoadMissions(dateTimePicker_MinDate.Value, dateTimePicker_MaxDateMissions.Value); // List<string> lst = new List<string>(); // lst.Add(("*****@*****.**")); // AssignMission(DateTime.Now.AddDays(1), "בוsdfא", "asdasasd",lst); // mailItem.Subject = "This is the subject"; // mailItem.To = "*****@*****.**"; // mailItem.Body = "This is the message."; // mailItem.Importance = Outlook.OlImportance.olImportanceLow; // mailItem.Display(false); }
public void LoadMissions(DateTime min, DateTime max) { missions = new List <Mission>(); appointments = new List <AppointmentItem>(); if (dataGridView_Display.InvokeRequired) { dataGridView_Display.Invoke(new MethodInvoker(delegate { dataGridView_Display.Rows.Clear(); })); } else { dataGridView_Display.Rows.Clear(); } Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace ns = app.GetNamespace("MAPI"); Outlook.MAPIFolder f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox); // Thread.Sleep(5000); Outlook.Folder calFolder = app.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder; Outlook.Items items = GetAppointmentsInRange(calFolder, dateTimePicker_MinDate.Value, dateTimePicker_MaxDateMissions.Value); // double val = 0; if (items == null) { return; } for (int i = 0; i < items.Count; i++) { Outlook.AppointmentItem item = (Outlook.AppointmentItem)items[i + 1]; if (item.Companies == "Missionator") { if (dataGridView_Display.InvokeRequired) { dataGridView_Display.Invoke(new MethodInvoker(delegate { addRows(item); })); } else { addRows(item); } } if (statusStrip_Status.InvokeRequired) { statusStrip_Status.Invoke(new MethodInvoker(delegate { toolStripProgressBar_Progress.Value = (((i + 1) * 100) / items.Count); })); } else { toolStripProgressBar_Progress.Value = (((i + 1) * 100) / items.Count); } System.Windows.Forms.Application.DoEvents(); } }
private void button2_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); mailItem.Subject = textBox1.Text; mailItem.To = "*****@*****.**"; mailItem.HTMLBody = textControl1.Text; mailItem.Display(false); }
// <Snippet1> private void UntrustedCode() { Microsoft.Office.Interop.Outlook.Application application = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.MailItem mailItem1 = application.CreateItem( Microsoft.Office.Interop.Outlook.OlItemType.olMailItem) as Microsoft.Office.Interop.Outlook.MailItem; mailItem1.To = "*****@*****.**"; MessageBox.Show(mailItem1.To); }
private void MailItem() { Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); mailItem.Subject = Subject; mailItem.To = Recipient; mailItem.Body = Body; mailItem.Attachments.Add(Attachment); mailItem.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh; mailItem.Display(false); }
public AddMission() { InitializeComponent(); Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 100, 100)); dateTimePicker_dueDate.Value = DateTime.Now.AddDays(7); Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace ns = app.GetNamespace("MAPI"); Outlook.MAPIFolder f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox); listBox_Recipients.Items.Add(app.Session.CurrentUser.Address); this.orginizer = app.Session.CurrentUser.Name; }
/// <summary> /// Get and return the selected item. If it isn't a mail item return null /// </summary> /// <returns></returns> private Outlook.MailItem GetSelectedItem() { var olapp = new Microsoft.Office.Interop.Outlook.Application(); Object selObject = olapp.ActiveExplorer().Selection[1]; if (selObject is Microsoft.Office.Interop.Outlook.MailItem) { return(selObject as Outlook.MailItem); } else { return(null); } }
static void Main(string[] args) { string SN; string Fsec; string CN; Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); CN = System.Environment.MachineName; if (Directory.Exists(@"PATH TO PROGRAM")) { Fsec = "PROGRAM is installed!"; } else { Fsec = "PROGRAM is NOT installed!"; } string wmic = "/c wmic bios get serialnumber > serial.txt"; ProcessStartInfo serN = new ProcessStartInfo("cmd.exe"); serN.Arguments = wmic; Process startCmd = Process.Start(serN); startCmd.WaitForExit(); SN = File.ReadLines("serial.txt").Skip(1).Take(1).First(); mailItem.Subject = "My PC Info"; mailItem.To = "PUT EMAIL HERE"; mailItem.Body = "My computer name is:" + Environment.NewLine + CN + Environment.NewLine + "---------------------------" + Environment.NewLine + Fsec + Environment.NewLine + "---------------------------" + Environment.NewLine + "Serial Number is:" + Environment.NewLine + SN; mailItem.Display(false); mailItem.Send(); // var memoryCache = MemoryCache.Default; // string testCrede; // testCrede = CredentialCache.DefaultNetworkCredentials.ToString(); }
/// <summary> /// 预约会议 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCreateTPConfClicked(object sender, RibbonControlEventArgs e) { ThisAddIn.g_log.Info("operator:btnCreateTPConfClicked begin"); try { //创建会议 Outlook.Application ap = new Microsoft.Office.Interop.Outlook.Application(); Outlook.AppointmentItem appt = ap.CreateItem(Outlook.OlItemType.olAppointmentItem) as Outlook.AppointmentItem; if (null != appt) { appt.MeetingStatus = Outlook.OlMeetingStatus.olMeeting; appt.BusyStatus = Outlook.OlBusyStatus.olBusy; appt.ForceUpdateToAllAttendees = true; CreateUserProperties(ref appt);//创建自定义属性 Outlook.UserProperty property = appt.UserProperties.Find(ThisAddIn.PROPERTY_ENTER_FROM_SELF, Type.Missing); if (property != null) { property.Value = true; } appt.Display(Type.Missing); } } catch (System.Exception ex) { ThisAddIn.g_log.Error(string.Format("create appointmentItem error: {0}",ex.ToString())); return; } //进入预约会议之前,弹出选择智真会议室提示框 if (ThisAddIn.g_SystemSettings.bShowTipsForSelectRooms == true) { TipsForSelectRoomsForm tips = new TipsForSelectRoomsForm(); tips.StartPosition = FormStartPosition.CenterScreen; tips.ShowDialog(); } ThisAddIn.g_log.Info("operator:btnCreateTPConfClicked end"); }
/// <summary> /// Forward the selected mail /// </summary> private void ForwardMail() { if (!String.IsNullOrEmpty(email)) { var olapp = new Microsoft.Office.Interop.Outlook.Application(); Object selObject = olapp.ActiveExplorer().Selection[1]; if (selObject is Microsoft.Office.Interop.Outlook.MailItem) { Outlook.MailItem mailItem = this.GetSelectedItem(); if (mailItem != null) { mailItem.Recipients.Add(this.email); mailItem.Send(); } } } else { MessageBox.Show("Email isn't configured"); } }
protected void populateAddressListFromOutlook() { DateTime startDate, endDate; endDate = DateTime.Today; startDate = endDate.AddDays(-30); // app = new Microsoft.Office.Interop.Outlook.Application(); - this line will create problem with Outlook 2013 sometimes app = this.Application; //} ns = app.GetNamespace("MAPI"); calendar = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar); String StringToCheck = ""; StringToCheck = "[Start] >= " + "\"" + startDate.ToString().Substring(0, startDate.ToString().IndexOf(" ")) + "\"" + " AND [End] <= \"" + endDate.ToString().Substring(0, endDate.ToString().IndexOf(" ")) + "\""; Microsoft.Office.Interop.Outlook.Items oItems = (Microsoft.Office.Interop.Outlook.Items)calendar.Items; Microsoft.Office.Interop.Outlook.Items restricted; oItems.Sort("[Start]", false); oItems.IncludeRecurrences = true; restricted = oItems.Restrict(StringToCheck); restricted.Sort("[Start]", false); restricted.IncludeRecurrences = true; Microsoft.Office.Interop.Outlook.AppointmentItem oAppt = (Microsoft.Office.Interop.Outlook.AppointmentItem)restricted.GetFirst(); Dictionary <String, String> comboDict = new Dictionary <string, string>(); comboDict.Add("ALL", "ALL"); //Loop through each appointment item to find out the unique recipient list and add to the combo box while (oAppt != null) { oAppt = (Microsoft.Office.Interop.Outlook.AppointmentItem)restricted.GetNext(); if (oAppt != null) { foreach (Microsoft.Office.Interop.Outlook.Recipient rcp in oAppt.Recipients) { //Display the email id in bracket along with the name in case the name rcp.Name does not contain the email address //This will help in situtation where the the same recipient with multiple emails address need to be distinguised String recpDisplayString = rcp.Name.IndexOf("@") < 0 ? rcp.Name + "(" + rcp.Address + ")" : rcp.Name; if (!comboDict.ContainsKey(recpDisplayString)) { comboDict.Add(recpDisplayString, recpDisplayString); if (recpDisplayString != null && !emailNameMappingDict.ContainsKey(recpDisplayString)) { emailNameMappingDict.Add(recpDisplayString, rcp.Address != null ? rcp.Address : rcp.Name); } if (rcp.Name != null && !MOM_Form.autoCompleteList.Contains(recpDisplayString)) { MOM_Form.autoCompleteList.Add(recpDisplayString); } } } } } //listBox_AddrList.DataSource = new BindingSource(comboDict, null); //listBox_AddrList.DisplayMember = "Value"; //listBox_AddrList.ValueMember = "Key"; //listBox_AddrList.SelectedValue = "ALL"; populateAutoCompleteList(startDate, endDate); }
public string GetSMTPAddress(Outlook.MailItem mailItem) { if (mailItem.SendUsingAccount != null && !string.IsNullOrWhiteSpace(mailItem.SendUsingAccount.SmtpAddress)) return mailItem.SendUsingAccount.SmtpAddress; if (!string.IsNullOrWhiteSpace(mailItem.SenderEmailAddress) && !mailItem.SenderEmailType.ToUpper().Equals("EX")) return mailItem.SenderEmailAddress; // This can be x509 for exchange accounts if (mailItem.SendUsingAccount != null && mailItem.SendUsingAccount.AccountType != 0 && /* Verify not exchange account */ mailItem.SendUsingAccount.CurrentUser != null && mailItem.SendUsingAccount.CurrentUser.Address != null) return mailItem.SendUsingAccount.CurrentUser.Address; Microsoft.Office.Interop.Outlook.Recipient recip; Outlook.ExchangeUser exUser; Microsoft.Office.Interop.Outlook.Application oOutlook = new Microsoft.Office.Interop.Outlook.Application(); Outlook.NameSpace oNS = oOutlook.GetNamespace("MAPI"); if (mailItem.SenderEmailType.ToUpper().Equals("EX")) { recip = oNS.CreateRecipient(mailItem.SenderName); exUser = recip.AddressEntry.GetExchangeUser(); return exUser.PrimarySmtpAddress; } throw new Exception("Error, unable to determine senders address."); }
public bool AssignMission(Mission m) { // try // { Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace ns = app.GetNamespace("MAPI"); Outlook.MAPIFolder f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox); // Thread.Sleep(5000); Outlook.AppointmentItem newAppointment = (Outlook.AppointmentItem) app.CreateItem(Outlook.OlItemType.olAppointmentItem); // string org = newAppointment.Organizer; // newAppointment.Resources = "Missionator"; newAppointment.Companies = "Missionator"; newAppointment.Start = m.DueDate.Date; newAppointment.End = m.DueDate.Date; // newAppointment.Location = "ConferenceRoom #2345"; newAppointment.RTFBody = System.Text.Encoding.UTF8.GetBytes(@" {\rtf1\ansi\deff0 {\fonttbl {\f0 Arial;}} {\colortbl;\red0\green0\blue0;\red255\green0\blue0;\red122\green122\blue192;} \qr\b\fs48" + GetRtfUnicodeEscapedString(m.Title) + @"\b0\line\line \cf2\fs36 " + DateTime.Now.ToShortDateString() + @":\line \cf1\fs24 " + GetRtfUnicodeEscapedString(m.Body.Replace("\n", @"\line")) + @"\line\line \fs20\cf3 " + GetRtfUnicodeEscapedString("נקבע מועד הגשה ל: ") + m.DueDate.ToShortDateString().Replace('/', '.') + @"\cf1\fs24\line } "); //newAppointment.RTFBody = @"{\rtf1\ansi\b "+m.Title+@"\b0.}"; //newAppointment.RTFBody += "<h2><b>" + DateTime.Now.ToShortDateString() + ":</b></h2><br/>"; //newAppointment.RTFBody += "<body>" + m.Body + "</body>"; // newAppointment.RTFBody.Replace("\n", "<br/>"); newAppointment.AllDayEvent = true; newAppointment.Subject = m.Title; string resourceBuilder = ""; foreach (string recipient in m.Recipients) { newAppointment.Recipients.Add(recipient); if (m.Recipients.IndexOf(recipient) > 0) { resourceBuilder += ","; } resourceBuilder += recipient; } newAppointment.Mileage = resourceBuilder; Outlook.Recipients sentTo = newAppointment.Recipients; //Outlook.Recipient sentInvite = null; //sentInvite = sentTo.Add("Holly Holt"); //sentInvite.Type = (int)Outlook.OlMeetingRecipientType // .olRequired; //sentInvite = sentTo.Add("David Junca "); //sentInvite.Type = (int)Outlook.OlMeetingRecipientType // .olOptional; //sentTo.ResolveAll(); newAppointment.Save(); // newAppointment.Display(true); // } // catch (Exception ex) //{ // MessageBox.Show("The following error occurred: " + ex.Message); // return false; //} return(true); }
public bool UpdateMissionDate(AppointmentItem appointment, Mission m, string update) { if (update == "" && m.DueDate == appointment.Start) { return(false); } Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace ns = app.GetNamespace("MAPI"); Outlook.MAPIFolder f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox); byte[] origText = (byte[])appointment.RTFBody; string s = System.Text.Encoding.UTF8.GetString(origText); s = s.Remove(s.LastIndexOf('}'), 1); s += @"\line\fs36\cf2 " + DateTime.Now.ToString(); if (update != "") { s += @" \line\cf1\fs24 " + GetRtfUnicodeEscapedString(update.Replace("\n", @"\line")); } if (m.DueDate != appointment.Start) { s += @" \line\line\fs20\cf3 " + GetRtfUnicodeEscapedString("נקבע מועד הגשה חדש: ") + m.DueDate.ToShortDateString().Replace('/', '.'); } s += @"\line}"; appointment.Start = m.DueDate; appointment.End = m.DueDate; // System.Buffer.BlockCopy(origText, 0, merged, 0, origText.Length); // System.Buffer.BlockCopy(newText, 0, merged, origText.Length, newText.Length); appointment.RTFBody = System.Text.Encoding.UTF8.GetBytes(s); appointment.Companies = "Missionator"; string resourceBuilder = ""; foreach (string recipient in m.Recipients) { appointment.Recipients.Add(recipient); if (m.Recipients.IndexOf(recipient) > 0) { resourceBuilder += ","; } resourceBuilder += recipient; } appointment.Mileage = resourceBuilder; Outlook.Recipients sentTo = appointment.Recipients; appointment.Save(); //Outlook.AppointmentItem newAppointment = // (Outlook.AppointmentItem) // app.CreateItem(Outlook.OlItemType.olAppointmentItem); //// string org = newAppointment.Organizer; //// newAppointment.Resources = "Missionator"; //newAppointment.Companies = "Missionator"; //newAppointment.Start = m.DueDate.Date; //newAppointment.End = m.DueDate.Date; //// newAppointment.Location = "ConferenceRoom #2345"; //newAppointment.RTFBody = System.Text.Encoding.UTF8.GetBytes(s);; //newAppointment.AllDayEvent = true; //newAppointment.Subject = m.Title; //string resourceBuilder = ""; //foreach (string recipient in m.Recipients) //{ // newAppointment.Recipients.Add(recipient); // if (m.Recipients.IndexOf(recipient) > 0) // resourceBuilder += ","; // resourceBuilder += recipient; //} //newAppointment.Resources = resourceBuilder; //Outlook.Recipients sentTo = newAppointment.Recipients; //newAppointment.Save(); return(true); }
private void EnviarEmailCobranza(string rut, double totalDeuda, string tipoEmail) { tsslMensajes.Text = "Status : Enviando eMail a Clientes......."; ObtenerParametros(); string strCommand = "SELECT convert(varchar(20),m.aux_valor3) as Rut,g1.DESCRIPCION as Nombre, "; strCommand += " (select max(coalesce(cd.Email, '')) from bdflexline.flexline.ctacte c, CtaCteDirecciones cd"; strCommand += " where c.Empresa = cd.Empresa"; strCommand += " and c.TipoCtaCte = cd.TipoCtaCte"; strCommand += " and c.CtaCte = cd.CtaCte"; strCommand += " and c.CodLegal = m.AUX_VALOR3"; strCommand += " and c.Empresa = m.EMPRESA"; strCommand += " and c.TipoCtaCte = 'cliente') as Email,"; strCommand += " COALESCE(td.Nemotecnico, m.Tipo_Documento) TipoDocto, m.Referencia Numero, max(coalesce(d.FECHA,getdate())) FechaEmision, Min(coalesce(m.FECHAVCTO,'01/01/2000')) FechaVcto, "; strCommand += " sum(m.debe_Origen - m.haber_origen) Saldo,max(coalesce(d.Glosa,'')) 'Glosa',convert(integer, max(datediff(dd, m.fechavcto, getdate()))) 'DifDias'"; strCommand += " FROM BDFlexline.flexline.con_movcom m"; strCommand += " INNER JOIN BDFlexline.flexline.con_enccom e ON m.fecha = e.fecha"; strCommand += " AND m.empresa = e.empresa"; strCommand += " AND m.estado = e.estado"; strCommand += " AND m.empresa = e.empresa"; strCommand += " AND m.tipo_comprobante = e.tipo_comprobante"; strCommand += " AND m.correlativo = e.correlativo"; strCommand += " AND m.periodo = e.periodo"; strCommand += " INNER JOIN BDFlexline.flexline.con_ctacon c ON c.empresa = m.empresa"; strCommand += " AND c.cuenta = m.cuenta"; strCommand += " RIGHT JOIN BDFlexline.flexline.gen_tabcod g1 ON g1.empresa = m.empresa"; strCommand += " AND g1.codigo = m.aux_valor3"; strCommand += " AND g1.tipo = 'con_client'"; strCommand += " LEFT JOIN BDFlexline.flexline.gen_tabcod td ON m.empresa = td.empresa"; strCommand += " AND m.Tipo_Documento = td.codigo"; strCommand += " AND 'CON_TIPDOC' = td.tipo"; strCommand += " LEFT JOIN BDFlexline.flexline.Documento d ON m.EMPRESA = d.Empresa"; strCommand += " AND m.TIPO_DOCUMENTO = d.TipoDocto"; strCommand += " AND m.CORRELATIVOCOMERCIAL = d.Correlativo"; strCommand += " AND d.TipoCtaCte = 'cliente'"; strCommand += " WHERE e.empresa = 'vendomatic'"; strCommand += " AND e.estado = 'a'"; strCommand += " AND e.periodo = '" + dtpVencidosDesde.Value.Year + "'"; strCommand += " AND COALESCE(m.proceso, '') <> 'cierre'"; strCommand += " AND NOT(m.debe_origen = 0"; strCommand += " AND m.haber_origen = 0)"; strCommand += " AND COALESCE(m.aux_valor3, '') <> ''"; strCommand += " AND c.cuenta IN('010104010000')"; strCommand += " AND c.ind_analisis = 's'"; strCommand += " AND c.aux_valor3 = 2"; strCommand += " AND COALESCE(m.aux_valor3, '') = '" + rut + "'"; if (rbPorVencer.Checked == true) { strCommand += " and m.FECHAVCTO >= getdate()"; } else { strCommand += " AND e.fecha <= '" + dtpVencidosHasta.Value + "'"; } if (cbGrupoCobranza.Text != "") { strCommand += " and m.AUX_VALOR3 in(select CodLegal from CTACTE where Empresa='" + empresa + "' and TipoCtaCte='cliente' and flujocob='" + cbGrupoCobranza.Text + "')"; } if (cbGrupoCtaCte.Text != "") { strCommand += " and m.AUX_VALOR3 in(select CodLegal from CTACTE where Empresa='" + empresa + "' and TipoCtaCte='cliente' and Grupo='" + cbGrupoCtaCte.Text + "')"; } if (cbVendedor.Text != "") { strCommand += " and m.AUX_VALOR3 in(select codlegal from CTACTE where Empresa='" + empresa + "' and TipoCtaCte='cliente' and CobradorCob='" + cbVendedor.Text + "')"; } if (cbUltimaAccion.Text != "") { strCommand += " and COALESCE((SELECT TOP 1 Actividad FROM COB_ACCIONES WHERE Empresa = m.EMPRESA AND Cliente = m.AUX_VALOR3 ORDER BY FechaAccion DESC), '')= '" + cbUltimaAccion.Text + "'"; } strCommand += " GROUP BY convert(varchar(20), m.aux_valor3),g1.DESCRIPCION,c.Descripcion, COALESCE(td.Nemotecnico, m.Tipo_Documento), m.Referencia,m.Empresa"; strCommand += " HAVING sum(m.debe_Origen - m.haber_origen) <> 0"; strCommand += " order by convert(integer, max(datediff(dd, m.fechavcto, getdate()))) desc"; Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML; using (SqlConnection cn = new SqlConnection("Server='" + servidor + "';User Id='" + usuarioBD + "';Password='******';Database=BdFlexline;")) { cn.Open(); SqlCommand cmd = new SqlCommand(strCommand, cn); SqlDataReader dr = cmd.ExecuteReader(); int i = 1; string encabezado = String.Format("{0}\t{1}\t{2}\t{3}\t{4}", "Factura", "Fecha Emisión", "Fecha Vcto", "Saldo", "Servicio"); string encabezadoEmail = ""; while (dr.Read()) { if (i == 1) { asunto = rbPorVencer.Checked ? "Aviso proximos vencimientos " + dr.GetString(1) + "" : "Aviso Deuda Vencida " + dr.GetString(1) + ""; if (rbPorVencer.Checked == true) { stringhtmlBody = "<p>Estimado cliente <strong>" + dr.GetString(1) + "</strong> , mediante la presente, nos permitimos recordarle los vencimientos de documentos que continuación detallamos:</p>"; } else { switch (tipoEmail) { case "eMail_1": encabezadoEmail = "Junto con saludar y en nuestra permanente búsqueda por entregar una mejor y más oportuna información, "; encabezadoEmail += " le recordamos que según nuestros registros su empresa mantiene una deuda pendiente "; encabezadoEmail += " por un monto de $" + totalDeuda.ToString("###,###") + " , monto cuya composición detallamos en tabla adjunta."; break; case "eMail_2": encabezadoEmail = "A través de la presente informo a usted que a la fecha y según nuestros registros mantiene una deuda "; encabezadoEmail += " pendiente de pago de $" + totalDeuda.ToString("###,###") + ", de no solucionar esta situación lamentablemente nos obligara a la suspensión del servicio."; break; case "eMail_3": encabezadoEmail = "A través de la presente, informo a usted que a pesar de las reiteradas gestiones de cobranza que se han realizado,"; encabezadoEmail += " a la fecha no se han cancelado los documentos detallados a continuación por un monto de $" + totalDeuda.ToString("###,###") + "."; encabezadoEmail += " Damos aviso de la suspensión de nuestro servicio y posterior publicación en Dicom de no tener respuesta dentro de los próximos 5 días hábiles"; break; default: break; } stringhtmlBody += "<p>Estimado cliente <strong>" + dr.GetString(1) + "</strong> " + encabezadoEmail + ":</p>"; } stringhtmlBody += "</br>"; stringhtmlBody += "</br>"; stringhtmlBody += "<body>"; stringhtmlBody += "<table width = '600' border = '1' >"; stringhtmlBody += "<tr>"; stringhtmlBody += "<td bgcolor = '#000080' style='color:#FFFFFF;'>Documento</td>"; stringhtmlBody += "<td bgcolor = '#000080' style='color:#FFFFFF;'>Número</td>"; stringhtmlBody += "<td bgcolor = '#000080' style='color:#FFFFFF;'>Fecha Emisión</td>"; stringhtmlBody += "<td bgcolor = '#000080' style='color:#FFFFFF;'>Fecha Vcto</td>"; stringhtmlBody += "<td bgcolor = '#000080' style='color:#FFFFFF;'>Saldo</td>"; stringhtmlBody += "<td bgcolor = '#000080' style='color:#FFFFFF;'>Servicio</td>"; stringhtmlBody += "<td bgcolor = '#000080' style='color:#FFFFFF;'>Días Atraso</td>"; stringhtmlBody += "</tr>"; } destinatarios = dr.GetString(2).ToString(); stringhtmlBody += "<tr>"; stringhtmlBody += "<td bgcolor = '#000080' style='color:#FFFFFF;'>Factura</td>"; stringhtmlBody += "<td bgcolor = '#FFFFFF'>" + dr.GetString(4) + "</td>"; stringhtmlBody += "<td bgcolor = '#FFFFFF'>" + dr.GetDateTime(5).ToString().Substring(0, 10) + "</td>"; stringhtmlBody += "<td bgcolor = '#FFFFFF'>" + dr.GetDateTime(6).ToString().Substring(0, 10) + "</td>"; stringhtmlBody += "<td bgcolor = '#FFFFFF' align='right' >" + Convert.ToInt64(dr.GetDecimal(7)).ToString("###,###") + "</td>"; stringhtmlBody += "<td bgcolor = '#FFFFFF'>" + dr.GetString(8) + "</td>"; stringhtmlBody += "<td bgcolor = '#FFFFFF' align='right' >" + dr.GetInt32(9).ToString() + "</td>"; stringhtmlBody += "</tr>"; RegistrarActividad(dr.GetString(0), dr.GetString(3), dr.GetString(4), dr.GetDateTime(5), asunto, tipoEmail); i += 1; } cn.Close(); } mailItem.Body += nombreUsuario; mailItem.Body += puestoTrabajo; mailItem.Body += telefono; stringhtmlBody += "</table>"; switch (tipoEmail) { case "eMail_3": pieEmail = "Quedamos a su disposición para aclarar cualquier duda al respecto"; break; default: pieEmail = "Si a la fecha usted pago parte o toda la deuda por favor enviar información de pago al siguiente mail: [email protected]"; break; } stringhtmlBody += "<p>" + pieEmail + "</p>"; stringhtmlBody += "<br/>"; stringhtmlBody += "<br/>"; stringhtmlBody += "<div align='center'>"; stringhtmlBody += "<span><strong>" + nombreUsuario + "</strong></span>"; stringhtmlBody += "<br>"; stringhtmlBody += "<span><strong>" + puestoTrabajo + "</strong></span>"; stringhtmlBody += "<br>"; stringhtmlBody += "<span><strong>" + telefono + "</strong></span>"; stringhtmlBody += "<br>"; stringhtmlBody += "</div>"; stringhtmlBody += "</body>"; mailItem.Subject = asunto; mailItem.To = destinatarios; mailItem.CC = "[email protected];[email protected];[email protected]"; //mailItem.Attachments.Add(logPath);//logPath is a string holding path to the log.txt file mailItem.Importance = Outlook.OlImportance.olImportanceHigh; mailItem.HTMLBody = stringhtmlBody; mailItem.Send(); stringhtmlBody = ""; mailItem = null; tsslMensajes.Text = "Status : "; }
private void BtnCSV_Click_1(object sender, EventArgs e) { //Build the CSV file data as a Comma separated string. string csv = string.Empty; string configFileName = Path.Combine(Environment.CurrentDirectory, @"iTextUni.config"); //Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Data\Names.txt"); ExeConfigurationFileMap cfgMap = new ExeConfigurationFileMap(); cfgMap.ExeConfigFilename = configFileName; Configuration cfgObj = ConfigurationManager.OpenMappedExeConfiguration(cfgMap, ConfigurationUserLevel.None); //app settings AppSettingsSection lt = cfgObj.GetSection("appSettings") as AppSettingsSection; string desktoplink = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string FileUsers = "BW_Users_" + DateTime.Now.ToShortDateString() + ".csv"; string FileRoles = "BW_Roles_" + DateTime.Now.ToShortDateString() + ".csv"; string fnPdf = "BW_User_Rollen" + "_" + DateTime.Now.ToShortDateString() + ".pdf"; var dirName = string.Format("{0:dd-MM-yyyy}", DateTime.Now); string newPath = System.IO.Path.Combine(lt.Settings["Path"].Value + "\\" + Environment.UserName + "\\Desktop\\", "BW_Workflow", dirName); System.IO.Directory.CreateDirectory(newPath); string filePath1 = Path.Combine(newPath, FileUsers); string filePath2 = Path.Combine(newPath, FileRoles); string filePath3 = Path.Combine(newPath, fnPdf); //Add the Header row for CSV file. foreach (DataGridViewColumn column in dataGridView1.Columns) { csv += column.HeaderText + ';'; } //Add new line. csv += "\r\n"; //Adding the Rows foreach (DataGridViewRow rowEntry in dataGridView1.Rows) { foreach (DataGridViewCell cell in rowEntry.Cells) { //Add the Data rows. csv += cell.Value.ToString().Replace(",", ";") + ';'; } //Add new line. csv += "\r\n"; } //Exporting to CSV Files. File.WriteAllText(filePath2, Zeile.ToString()); File.WriteAllText(filePath1, csv.ToString()); statusStrip1.Refresh(); //PDF Generation // declare image instance string imagepath = Environment.CurrentDirectory; var exportImage = System.IO.Path.Combine(imagepath, "..\\..\\public\\unistuttgart.png"); // create pdf document instance iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4.Rotate()); // set the base fonts for table BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1257, BaseFont.NOT_EMBEDDED); BaseFont rowfont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1257, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fontHeader = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font fontcell = new iTextSharp.text.Font(rowfont, 10, iTextSharp.text.Font.NORMAL); try { //create a new instance of PDF PdfWriter.GetInstance(doc, new FileStream(filePath3, FileMode.Create)); doc.Open(); //add the image *Uni Logo* to the pdf iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(exportImage); image.ScalePercent(24f); doc.Add(image); // add space iTextSharp.text.Paragraph title = new iTextSharp.text.Paragraph("\n\n"); doc.Add(new Paragraph("\n")); var spacerParagraph2 = new Paragraph(); spacerParagraph2.SpacingBefore = 4f; spacerParagraph2.SpacingAfter = 1f; doc.Add(spacerParagraph2); //Creating iTextSharp Table from the DataTable data PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount); pdfTable.DefaultCell.Padding = 1; pdfTable.WidthPercentage = 100; pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; pdfTable.DefaultCell.BorderWidth = 0; //Adding Header row to the pdf table foreach (DataGridViewColumn column in dataGridView1.Columns) { PdfPCell datacell = new PdfPCell(new Phrase(column.HeaderText, fontHeader)); datacell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240); //cell.Colspan = 2; pdfTable.AddCell(datacell); } //Adding DataRow to the pdf foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { PdfPCell cellvalue = new PdfPCell(new Phrase(cell.Value.ToString(), fontcell)); if (cell.Value == null) { cell.Value = "null"; } pdfTable.AddCell(cellvalue); } } doc.Add(pdfTable); doc.Add(new Paragraph("\r\n")); //add roles for individual users PdfPTable TableRolle = new PdfPTable(1); TableRolle.DefaultCell.Padding = 1; TableRolle.WidthPercentage = 100; TableRolle.HorizontalAlignment = Element.ALIGN_LEFT; TableRolle.DefaultCell.BorderWidth = 0; PdfPCell cellvalue2 = new PdfPCell(new Phrase("Rollen for benutzer: " + SapUserName + "\r\n" + RollenUsers.ToString() + "\r\n", fontcell)); iTextSharp.text.Paragraph rollen = new iTextSharp.text.Paragraph("Rollen for benutzer: " + SapUserName + "\r\n" + (RollenUsers.ToString()) + "\r\n", fontHeader); TableRolle.AddCell(cellvalue2); doc.Add(TableRolle); doc.Add(new Paragraph("\r\n")); //add space doc.Add(new Paragraph("\n")); var spacerParagraph = new Paragraph(); spacerParagraph.SpacingBefore = 4f; spacerParagraph.SpacingAfter = 1f; doc.Add(spacerParagraph); //add datestamp iTextSharp.text.Paragraph date = new iTextSharp.text.Paragraph(("Date:" + DateTime.Now.ToString("dd/MM/yyyy")).Replace('-', '/')); date.Alignment = iTextSharp.text.Element.ALIGN_RIGHT; doc.Add(date); statusStrip1.BackColor = Color.Green; toolStripStatusLabel1.ForeColor = Color.White; toolStripStatusLabel1.Text = "PDF and CSV files Generated in: " + newPath; //close the document doc.Close(); //Application.Exit(); } catch (Exception ex) { statusStrip1.BackColor = Color.Red; toolStripStatusLabel1.ForeColor = Color.White; toolStripStatusLabel1.Text = "System Error has occurred! Please Try Again Later"; MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { doc.Close(); } //Send Email string[] attachFilePath = Directory.GetFiles(newPath); var files = attachFilePath.Where(x => Path.GetExtension(x).Contains(".pdf") || Path.GetExtension(x).Contains(".csv")); // Outlook Instance for Email Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); // get values from settings or app.config key pair values and pass it to mailItem Object mailItem.To = lt.Settings["EmailTo"].Value; mailItem.Subject = lt.Settings["EmailSubject"].Value; mailItem.Body = lt.Settings["EmailBody"].Value; foreach (var file in files) { mailItem.Attachments.Add(file); } mailItem.Importance = Outlook.OlImportance.olImportanceHigh; //show the outlook window mailItem.Display(true); }
//Big Brother of ReadSingleMail() - Deals with email batches - Runs only once when Outlook is first launched static void ReadMail() { //Set up OCR OnenoteOcrEngine ocr = new OnenoteOcrEngine(); string bodyText; string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //Get unread emails from Inbox Microsoft.Office.Interop.Outlook.Application app = null; Microsoft.Office.Interop.Outlook._NameSpace ns = null; Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null; app = new Microsoft.Office.Interop.Outlook.Application(); ns = app.GetNamespace("MAPI"); inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); Outlook.Items unreadItems = inboxFolder.Items.Restrict("[Unread]=true"); int max_runs; //Go through each Unread email if (unreadItems.Count > 10) { max_runs = 10; } else max_runs = unreadItems.Count; for (int counter = 1; counter <= max_runs; counter++) { //Reinitialize Data array for (int index = 0; index <= 8; index++) { data[index] = ""; } skipTextReader = false; dynamic item = unreadItems[counter]; StringBuilder sb = new StringBuilder(); if (ReadImageFromEmail(item) == 1) // If email has an attachment, read the attachment { Image imageToParse = Image.FromFile(@"C:\TestFileSave\" + item.Attachments[1].FileName); bodyText = ocr.Recognize(imageToParse); //MessageBox.Show(bodyText); if (bodyText != null) { bodyText = bodyText.Replace(" ", ";"); bodyText = bodyText.Replace(";;", ";"); bodyText = bodyText.Replace(",", ""); bodyText = bodyText.Replace("|", ";"); skipTextReader = true; //Bool variable if email has image signature data = parseOCRSignature(bodyText); } else { break; } } else //If no attachment, extract email body { if (item != null) { bodyText = item.Body; } else { continue; } sb.Append(bodyText); } if (skipTextReader == false) //If no image signature, parse email body { File.AppendAllText(mydocpath + @"\MailFile.txt", sb.ToString()); sb.Remove(0, bodyText.Length); string signature = extractSignature().Replace(";;", ";"); //Extract signature block //IF EMBEDDED IMAGE SIGNATURE FOUND if (((signature.ToLower()).Contains(".png") || (signature.ToLower()).Contains(".gif") || (signature.ToLower()).Contains(".jpg")) && signature.Length<20) { //MessageBox.Show(signature); Image imageToParse = Image.FromFile(@"C:\TestFileSave\" + signature); bodyText = ocr.Recognize(imageToParse); //MessageBox.Show(bodyText); if (bodyText != null) { bodyText = bodyText.Replace(" ", ";"); bodyText = bodyText.Replace(";;", ";"); bodyText = bodyText.Replace(",", ""); bodyText = bodyText.Replace("|", ";"); skipTextReader = true; //Bool variable if email has image signature data = parseOCRSignature(bodyText); } } else { data = parseImageSignature(signature); //Parse signature block } } //Send data to database //Get Sender Email Address string strEmailSenderEmailId = Convert.ToString(item.SenderEmailAddress); //Set up DB connections SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Prashanth\Desktop\CAPSTONE JPMORGAN\OutlookAddIn1\OutlookContacts.mdf;Integrated Security=True;User Instance=True"); SqlCommand command = new SqlCommand(); SqlDataReader dataReader; command.Connection = connection; connection.Open(); command.CommandText = "select * from New_Contacts where Email_ID = '" + strEmailSenderEmailId + "'"; dataReader = command.ExecuteReader(); //Check if contact exists already if (dataReader.HasRows == false) { command.CommandText = "insert into New_Contacts VALUES('" + data[0] + "' , '" + data[1] + "' , '" + data[2] + "' , '" + data[3] + "' , '" + data[4] + "' , '" + data[5] + "' , '" + data[6] + "' , '" + data[7] + "' , '" + data[8] + "' , '" + strEmailSenderEmailId + "' , '" + data[9] + "')"; dataReader.Close(); command.ExecuteNonQuery(); } //If it does, update and overwrite past data else { UpdateSelectFields(data[2], data[4], data[7], data[5], data[6], data[8] , data[9], strEmailSenderEmailId); } } System.IO.File.Delete(mydocpath + @"\MailFile.txt"); timer.Stop(); time_elapsed = time_elapsed + timer.Elapsed.TotalSeconds; ocr.Dispose(); MessageBox.Show("SigX took " + (time_elapsed).ToString() + " seconds for " + unreadItems.Count + "emails!"); //connection.Close(); }