protected override ActivityExecutionStatus Execute(ActivityExecutionContext context) { // Create an Outlook Application object. Outlook.Application outlookApp = new Outlook.Application(); Outlook._MailItem oMailItem = (Outlook._MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem); oMailItem.To = outlookApp.Session.CurrentUser.Address; oMailItem.Subject = "Auto-Reply"; oMailItem.Body = "Out of Office"; //adds it to the outbox if (this.Parent.Parent is ParallelActivity) { if ((this.Parent.Parent.Parent.Activities[1] as DummyActivity).TitleProperty != "") { MessageBox.Show("Process Auto-Reply for Email"); oMailItem.Send(); } } else if (this.Parent.Parent is SequentialWorkflowActivity) { if ((this.Parent.Parent.Activities[1] as DummyActivity).TitleProperty != "") { MessageBox.Show("Process Auto-Reply for Email"); oMailItem.Send(); } } return(ActivityExecutionStatus.Closed); }
public static void SendEmailToSupport(Exception catchedException) { try { LoginInfo loginInfo = LoginInfo.GetInstance(); Outlook.Application outlookApp = GetApplicationObject(); Outlook._MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem); mailItem.Subject = loginInfo.UserName + "---ERROR: " + catchedException.Message; mailItem.Body = catchedException.ToString(); Outlook.Recipient recipient = (Outlook.Recipient)mailItem.Recipients.Add("*****@*****.**"); recipient.Resolve(); mailItem.Send(); recipient = null; mailItem = null; outlookApp = null; } catch (Exception e) { MessageBox.Show(e.Message); } }
public void OnSendList(Office.Core.IRibbonControl control) { if (control != null) { try { Outlook.Inspector inspector = (Outlook.Inspector)control.Context; String coffeeText = GetTextFromTaskPane(inspector); // Create a new email from the input parameters, and send it. Outlook._MailItem mi = (Outlook._MailItem) Globals.ThisAddIn.Application.CreateItem( Outlook.OlItemType.olMailItem); mi.Subject = _orderName; mi.Body = coffeeText; mi.To = _mailAddressee; mi.Send(); // Update the count of orders in the form region. UserInterfaceContainer uiContainer = Globals.ThisAddIn._uiElements.GetUIContainerForInspector( inspector); CultureInfo cultureInfo = new CultureInfo("en-us"); uiContainer.FormRegionControls.SetControlText( _ordersTextBoxName, (++_orderCount).ToString(cultureInfo)); } catch (COMException ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } } }
public void SendMail(string Subject, string ToAddress, string CCAddress, string Body, string Attachment, bool RequestReadReceipt) { Outlook._MailItem oMailItem = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); oMailItem.Recipients.Add(ToAddress); oMailItem.CC = CCAddress; oMailItem.BodyFormat = Outlook.OlBodyFormat.olFormatPlain; oMailItem.Subject = Subject; oMailItem.Body = Body; //oMailItem.SaveSentMessageFolder = oSentItemsFolder; oMailItem.ReadReceiptRequested = RequestReadReceipt; oMailItem.Attachments.Add(Attachment); if (oMailItem.Recipients.ResolveAll()) { if (Mode == "LIVE") { oMailItem.Send(); } else { oMailItem.Save(); } } else { throw new ApplicationException("Problem with recipient " + ToAddress); } }
private void SendEmail(Model.IEmail v_email) { OL._MailItem t_item = (OL._MailItem) this.m_outlook.CreateItem(OL.OlItemType.olMailItem); t_item.To = string.Join(";", v_email.TO.ToArray()); t_item.CC = string.Join(";", v_email.CC.ToArray()); t_item.Subject = v_email.Subject; t_item.Body = v_email.Body; //2009/6/6C³ OL.OlDefaultFolders.olFolderOutbox¨OL.OlDefaultFolders.olFolderSentMail t_item.SaveSentMessageFolder = this.m_outlook.Session.GetDefaultFolder(OL.OlDefaultFolders.olFolderSentMail); t_item.Send(); }
public static void sendEMailThroughOUTLOOK() { try { // Create the Outlook application. Outlook.Application oApp = new Outlook.Application(); // Create a new mail item. Outlook._MailItem oMsg = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); // Set HTMLBody. //add the body of the email // "Dear Admin, You have recieved an enquiry onyour Website. Following are the details of enquiry:<br/><br/>Name: " + TextBox2.Text + "<br/>Address: " + TextBox3.Text + ", " + TextBox4.Text + "<br/>Phone: " + TextBox5.Text + "<br/>Email: " + TextBox2.Text + "<br/>Query: " + TextBox6.Text+"<br/> Regards, <br/> Veritas Team" oMsg.HTMLBody = "Hi,\n \n <br/> <br/>Automation Execution has been started \n<br/><br/> Thanks & Regards \n<br/> Raghu Ram Reddy<br/><br/><br/>***This is an Auto generated mail***"; // oMsg.HTMLBody = "Automation Execution has been started!!"; //Add an attachment. String sDisplayName = "MyAttachment"; int iPosition = (int)oMsg.Body.Length + 1; int iAttachType = (int)Outlook.OlAttachmentType.olByValue; // now attached the file Outlook.Attachment oAttach = oMsg.Attachments.Add(@"D:\\Suite_Driver.xlsx", iAttachType, iPosition, sDisplayName); //Subject line oMsg.Subject = "Automation Execution has been started!!"; // Outlook.MailItem mail; // Add a recipient. Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients; // Change the recipient in the next line if necessary. // Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("*****@*****.**"); // oRecip.Resolve(); Outlook.Recipient oRecip2 = (Outlook.Recipient)oRecips.Add("*****@*****.**"); oRecip2.Resolve(); //Outlook.Recipient oRecip3 = (Outlook.Recipient)oRecips.Add("*****@*****.**"); //oRecip3.Resolve(); // Send. oMsg.Send(); // Clean up. oRecip2 = null; oRecips = null; oMsg = null; oApp = null; }//end of try block catch (Exception ex) { Console.WriteLine(ex); } //end of catch } //end of Email Method
public void SendMail(string Subject, string ToAddress, string CCAddress, string Body, List <string> Attachments, bool RequestReadReceipt, bool HighPriority) { Outlook._MailItem oMailItem = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); oMailItem.Recipients.Add(ToAddress); oMailItem.CC = CCAddress; oMailItem.BodyFormat = Outlook.OlBodyFormat.olFormatPlain; oMailItem.Subject = Subject; oMailItem.Body = Body; //oMailItem.SaveSentMessageFolder = oSentItemsFolder; oMailItem.ReadReceiptRequested = RequestReadReceipt; if (HighPriority) { oMailItem.Importance = Outlook.OlImportance.olImportanceHigh; } if (Attachments.Count > 0) { string thisAttachment; for (int i = 0; i <= Attachments.Count - 1; i++) { thisAttachment = Convert.ToString(Attachments[i]); if (thisAttachment != string.Empty) { oMailItem.Attachments.Add(thisAttachment); } } } if (oMailItem.Recipients.ResolveAll()) { if (Mode == "LIVE") { oMailItem.Send(); } else { oMailItem.Save(); } } else { throw new ApplicationException("Problem with recipient " + ToAddress); } }
/// <summary> /// Vérifie l'envoi de la proposition de mission. /// </summary> /// <param name="_message">Message</param> /// <returns>Boolean : True -> Réussite de l'envoi de l'email. False -> Echec de l'envoi de l'email</returns> private static bool IsSentEmail(_MailItem _message) { try { _MailItem message = _message; message.Send(); return(true); } catch { // Affichage d'un message d'erreur. MessageBox.Show(Results_Err.Default.IsSendEmail, Results_Err.Default.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } }
public void SendTestMail(string TestEmailAddress) { Outlook._MailItem oMailItem = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); oMailItem.To = TestEmailAddress; oMailItem.Subject = "Test"; oMailItem.Body = "Test"; //oMailItem.SaveSentMessageFolder = oSentItemsFolder; //oMailItem.Attachments.Add(@"C:\test.xml"); // uncomment this to also save this in your draft // oMailItem.Save(); // adds it to the outbox oMailItem.Send(); oMailItem = null /* TODO Change to default(_) if this is not a reference type */; }
/// <summary> /// Send Email Using Outlook /// </summary> /// <param name="toValue">Receipient Email Adress</param> /// <param name="subjectValue">Email Subject</param> /// <param name="bodyValue">Email Body</param> public void addToOutBox(string toValue, string subjectValue, string bodyValue) { try { Outlook._MailItem oMailItem = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); oMailItem.To = toValue; oMailItem.Subject = subjectValue; oMailItem.Body = bodyValue; oMailItem.SaveSentMessageFolder = oOutboxFolder; //uncomment this to also save this in your draft //oMailItem.Save(); //adds it to the outbox oMailItem.Send(); } catch { } }
public static void SendEmailTo_AssignedToUser(ProtocolRequest request, IList selectedTemplates) { try { LoginInfo loginInfo = LoginInfo.GetInstance(); Outlook.Application outlookApp = GetApplicationObject(); Outlook._MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem); mailItem.Subject = "Protocol Request #" + request.ID.ToString() + ": " + request.Contact.SponsorName; string body = @"A new protocol request has been submitted." + "\n\n" + "Request Details:" + "\n" + "Guidelines: " + request.Guidelines + "\n" + "Compliance: " + request.Compliance + "\n" + "Protocol Type: " + request.ProtocolType + "\n" + "VIA: " + request.SendVia + "\n" + "Comments: " + request.Comments + "\n" + "Contact Name: " + request.Contact.ContactName + "\n" + "Email: " + request.Contact.Email + "\n\n" + "Titles:" + "\n"; for (int i = 0; i < selectedTemplates.Count; i++) { Template title = selectedTemplates[i] as Template; body += (i + 1).ToString() + ": " + title.Title + "\n"; } mailItem.Body = body; Outlook.Recipient recipient = (Outlook.Recipient)mailItem.Recipients.Add("*****@*****.**"); recipient.Resolve(); mailItem.Send(); recipient = null; mailItem = null; outlookApp = null; } catch (Exception e) { ErrorHandler.CreateLogFile("EmailHandler", "SendEmailTo_AssignedToUser", e); } }
private void createAndSendEmail(string filePath, string fileName, string emailList) { try { Microsoft.Office.Interop.Outlook.Application oApp; Microsoft.Office.Interop.Outlook._NameSpace oNameSpace; Microsoft.Office.Interop.Outlook.MAPIFolder oOutboxFolder; oApp = new Microsoft.Office.Interop.Outlook.Application(); oNameSpace = oApp.GetNamespace("MAPI"); oNameSpace.Logon("", "", true, true); oOutboxFolder = oNameSpace.GetDefaultFolder( Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox); Microsoft.Office.Interop.Outlook._MailItem oMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem( Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); oMailItem.To = emailList; oMailItem.Subject = "Grocery Rescue Report From " + CCFBPrefs.FoodBankName; oMailItem.Body = "TEST THIS"; oMailItem.SaveSentMessageFolder = oOutboxFolder; String sSource = filePath; String sDisplayName = fileName; int iPosition = (int)oMailItem.Body.Length + 1; int iAttachType = (int)OlAttachmentType.olByValue; oMailItem.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName); //uncomment this to also save this in your draft //oMailItem.Save(); //adds it to the outbox oMailItem.Send(); oMailItem = null; oNameSpace = null; oApp = null; } catch (System.Exception ex) { CCFBGlobal.appendErrorToErrorReport("", ex.GetBaseException().ToString()); } }
private void createAndSendEmail(string filePath, string fileName, string emailList) { try { Microsoft.Office.Interop.Outlook.Application oApp; Microsoft.Office.Interop.Outlook._NameSpace oNameSpace; Microsoft.Office.Interop.Outlook.MAPIFolder oOutboxFolder; oApp = new Microsoft.Office.Interop.Outlook.Application(); oNameSpace = oApp.GetNamespace("MAPI"); oNameSpace.Logon("", "", true, true); oOutboxFolder = oNameSpace.GetDefaultFolder( Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox); Microsoft.Office.Interop.Outlook._MailItem oMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem( Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); oMailItem.To = emailList; oMailItem.Subject = fileName + " From " + tbFBName.Text; oMailItem.Body = "TEST THIS"; oMailItem.SaveSentMessageFolder = oOutboxFolder; String sSource = filePath; String sDisplayName = fileName; int iPosition = (int)oMailItem.Body.Length + 1; int iAttachType = (int)OlAttachmentType.olByValue; oMailItem.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName); //uncomment this to also save this in your draft //oMailItem.Save(); //adds it to the outbox oMailItem.Send(); oMailItem = null; oNameSpace = null; ////Create the new message by using the simplest approach. //MailItem oMsg = (MailItem)oApp.CreateItem(OlItemType.olMailItem); //Inspector oAddSig = null; ////oAddSig = oMsg.GetInspector; ////Add a recipient. //// TODO: Change the following recipient where appropriate. //Recipient oRecip = (Recipient)oMsg.Recipients.Add(emailList); //oRecip.Resolve(); ////Set the basic properties. //oMsg.Subject = fileName + " From " + tbFBName.Text; //oMsg.Body = "Put YOUR Message Here"; ////Add an attachment. //// TODO: change file path where appropriate //String sSource = filePath; //String sDisplayName = fileName; //int iPosition = (int)oMsg.Body.Length + 1; //int iAttachType = (int)OlAttachmentType.olByValue; //Attachment oAttach = oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName); //// If you want to, display the message. ////oMsg.Display(true); //modal ////Send the message. ////oMsg.Save(); //((Microsoft.Office.Interop.Outlook._MailItem)oMsg).Send(); //Explicitly release objects. //oRecip = null; //oAttach = null; //oMsg = null; oApp = null; } // Simple error handler. catch (System.Exception ex) { CCFBGlobal.appendErrorToErrorReport("", ex.GetBaseException().ToString()); } }
protected bool InviaMail(string nomeFoglio, object siglaEntita, List <Range> export) { string fileNameFull = ""; string fileName = ""; try { Excel.Worksheet ws = Globals.ThisWorkbook.Sheets[nomeFoglio]; DataView entitaProprieta = Workbook.Repository[DataBase.TAB.ENTITA_PROPRIETA].DefaultView; entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'SISTEMA_COMANDI_ALLEGATO_EXCEL' AND IdApplicazione = " + Workbook.IdApplicazione; if (entitaProprieta.Count > 0) { fileName = entitaProprieta[0]["Valore"] + "_VDT_" + Workbook.DataAttiva.ToString("yyyyMMdd") + ".xls"; fileNameFull = Environment.ExpandEnvironmentVariables(@"%TEMP%\" + fileName); //fileName = @"D:\" + entitaProprieta[0]["Valore"] + "_VDT_" + Workbook.DataAttiva.ToString("yyyyMMdd") + ".xls"; Excel.Workbook wb = Globals.ThisWorkbook.Application.Workbooks.Add(); int i = 2; foreach (Range rng in export) { ws.Range[rng.ToString()].Copy(); wb.Sheets[1].Range["B" + i++].PasteSpecial(); } wb.Sheets[1].Columns["B:C"].EntireColumn.AutoFit(); wb.Sheets[1].Range["A1"].Select(); wb.SaveAs(fileNameFull, Excel.XlFileFormat.xlExcel12); wb.Close(); Marshal.ReleaseComObject(wb); var config = Workbook.GetUsrConfigElement("destMailTest"); string mailTo = config.Test; string mailCC = ""; if (Workbook.Ambiente == Simboli.PROD) { entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'SISTEMA_COMANDI_MAIL_TO' AND IdApplicazione = " + Workbook.IdApplicazione; mailTo = entitaProprieta[0]["Valore"].ToString(); entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'SISTEMA_COMANDI_MAIL_CC' AND IdApplicazione = " + Workbook.IdApplicazione; mailCC = entitaProprieta[0]["Valore"].ToString(); } entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'SISTEMA_COMANDI_CODICE_MAIL' AND IdApplicazione = " + Workbook.IdApplicazione; string codUP = entitaProprieta[0]["Valore"].ToString(); config = Workbook.GetUsrConfigElement("oggettoMail"); string oggetto = config.Value.Replace("%COD%", codUP).Replace("%DATA%", Workbook.DataAttiva.ToString("dd-MM-yyyy")); config = Workbook.GetUsrConfigElement("messaggioMail"); string messaggio = config.Value; messaggio = Regex.Replace(messaggio, @"^[^\S\r\n]+", "", RegexOptions.Multiline); if (DataBase.OpenConnection()) { Outlook.Application outlook = GetOutlookInstance(); Outlook._MailItem mail = outlook.CreateItem(Outlook.OlItemType.olMailItem); //TODO check se manda sempre con lo stesso account... Outlook.Account senderAccount = outlook.Session.Accounts[1]; foreach (Outlook.Account account in outlook.Session.Accounts) { if (account.DisplayName == "Bidding") { senderAccount = account; } } mail.SendUsingAccount = senderAccount; mail.Subject = oggetto; mail.Body = messaggio; foreach (string dest in mailTo.Split(';')) { if (dest.Trim() != "") { mail.Recipients.Add(dest.Trim()); } } mail.CC = mailCC; mail.Attachments.Add(fileNameFull); mail.Send(); File.Delete(fileNameFull); } else { string emailFolder = @"C:\Emergenza\Email\" + Simboli.NomeApplicazione; if (!Directory.Exists(emailFolder)) { Directory.CreateDirectory(emailFolder); } File.Move(fileNameFull, Path.Combine(emailFolder, fileName)); } } } catch (Exception e) { Workbook.InsertLog(Core.DataBase.TipologiaLOG.LogErrore, "SistemaComandi.Esporta.InvioMail [" + siglaEntita + "]: " + e.Message); System.Windows.Forms.MessageBox.Show(e.Message, Simboli.NomeApplicazione + " - ERRORE!!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); if (File.Exists(fileNameFull)) { File.Delete(fileNameFull); } return(false); } return(true); }
protected bool InviaMail(string nomeFoglio, object siglaEntita, Range rng) { List <string> attachments = new List <string>(); bool hasVariations = false; try { Excel.Worksheet ws = Globals.ThisWorkbook.Sheets[nomeFoglio]; //inizializzo l'oggetto mail Outlook.Application outlook = GetOutlookInstance(); Outlook._MailItem mail = outlook.CreateItem(Outlook.OlItemType.olMailItem); DataView entitaProprieta = Workbook.Repository[DataBase.TAB.ENTITA_PROPRIETA].DefaultView; entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_ALLEGATO_EXCEL' AND IdApplicazione = " + Workbook.IdApplicazione; if (entitaProprieta.Count > 0) { //creo file Excel da allegare string excelExport = Path.Combine(@"C:\Emergenza", Workbook.DataAttiva.ToString("yyyyMMdd") + "_" + entitaProprieta[0]["Valore"] + "_" + Workbook.Mercato + ".xls"); attachments.Add(excelExport); hasVariations = CreaOutputXLS(ws, attachments.Last(), siglaEntita.Equals("CE_ORX"), rng); //25/01/2017 ENH: path export da file di configurazione var cfgPath = Workbook.GetUsrConfigElement("pathExportFileRosone"); //18/01/2017 FIX: inizializzazione fuori dall'if: provocava errore invio mail string pathExport = PreparePath(cfgPath); string fileNameXML = null; string fileNameCSV = null; string pathXmlOrcoExportFull = null; if (siglaEntita.Equals("CE_ORX")) { if (!Directory.Exists(pathExport)) { Directory.CreateDirectory(pathExport); } fileNameXML = fileNameCSV = "FMS_UP_ORCO_1_" + Workbook.Mercato + "D_" + Workbook.DataAttiva.ToString("yyyyMMdd"); fileNameXML += ".xml.OEIESRD.out.xml"; fileNameCSV += ".csv.OEIESRD.out.csv"; pathXmlOrcoExportFull = pathExport + "\\" + fileNameXML; bool xmlCreated = CreaOutputXML(siglaEntita, pathExport, fileNameXML, Workbook.DataAttiva); bool csvCreated = CreaOutputCSV(siglaEntita, pathExport, fileNameCSV, Workbook.DataAttiva); attachments.Add(Path.Combine(pathXmlOrcoExportFull)); } DataView categoriaEntita = Workbook.Repository[DataBase.TAB.CATEGORIA_ENTITA].DefaultView; categoriaEntita.RowFilter = "Gerarchia = '" + siglaEntita + "' AND IdApplicazione = " + Workbook.IdApplicazione; if (categoriaEntita.Count == 0) { categoriaEntita.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND IdApplicazione = " + Workbook.IdApplicazione; } bool interrupt = false; foreach (DataRowView entita in categoriaEntita) { entitaProprieta.RowFilter = "SiglaEntita = '" + entita["SiglaEntita"] + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_ALLEGATO_FMS' AND IdApplicazione = " + Workbook.IdApplicazione; if (entitaProprieta.Count > 0) { //cerco i file XML string nomeFileFMS = PrepareName(Workbook.GetUsrConfigElement("formatoNomeFileFMS").Value, codRup: entita["CodiceRup"].ToString()) + "*.xml"; string pathFileFMS = PreparePath(Workbook.GetUsrConfigElement("pathExportFileFMS")); string[] files = Directory.GetFiles(pathFileFMS, nomeFileFMS, SearchOption.TopDirectoryOnly); if (files.Length == 0) { if (!Workbook.DaConsole && System.Windows.Forms.MessageBox.Show("File FMS non presente nell'area di rete. Continuare con l'invio?", Simboli.NomeApplicazione + " - ATTENZIONE!!!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No) { interrupt = true; break; } } foreach (string file in files) { attachments.Add(file); //18/01/2017 FIX: non più utile per cambio requisiti //File.Copy(file, Path.Combine(pathExport, file.Split('\\').Last())); } } entitaProprieta.RowFilter = "SiglaEntita = '" + entita["SiglaEntita"] + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_ALLEGATO_RS' AND IdApplicazione = " + Workbook.IdApplicazione; if (entitaProprieta.Count > 0) { string nomeFileFMS = PrepareName(Workbook.GetUsrConfigElement("formatoNomeFileRS_TERNA").Value) + ".xml"; string pathFileFMS = PreparePath(Workbook.GetUsrConfigElement("pathExportFileRS")); string[] files = Directory.GetFiles(pathFileFMS, nomeFileFMS, SearchOption.TopDirectoryOnly); if (files.Length == 0) { if (!Workbook.DaConsole && System.Windows.Forms.MessageBox.Show("File Riserva Secondaria non presente nell'area di rete. Continuare con l'invio?", Simboli.NomeApplicazione + " - ATTENZIONE!!!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No) { interrupt = true; break; } } foreach (string file in files) { attachments.Add(file); //18/01/2017 FIX: non più utile per cambio requisiti //File.Copy(file, Path.Combine(pathExport, file.Split('\\').Last())); } } } if (!interrupt) { var config = Workbook.GetUsrConfigElement("destMailTest"); string mailTo = config.Test; string mailCC = ""; if (Workbook.Ambiente == Simboli.PROD) { entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_MAIL_TO' AND IdApplicazione = " + Workbook.IdApplicazione; mailTo = entitaProprieta[0]["Valore"].ToString(); entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_MAIL_CC' AND IdApplicazione = " + Workbook.IdApplicazione; mailCC = entitaProprieta[0]["Valore"].ToString(); } entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_CODICE_MAIL' AND IdApplicazione = " + Workbook.IdApplicazione; string codUP = entitaProprieta[0]["Valore"].ToString(); config = Workbook.GetUsrConfigElement("oggettoMail"); string oggetto = config.Value.Replace("%COD%", codUP).Replace("%DATA%", Workbook.DataAttiva.ToString("dd-MM-yyyy")).Replace("%MSD%", Workbook.Mercato) + (hasVariations ? " - CON VARIAZIONI" : ""); config = Workbook.GetUsrConfigElement("messaggioMail"); string messaggio = config.Value; messaggio = Regex.Replace(messaggio, @"^[^\S\r\n]+", "", RegexOptions.Multiline); //TODO check se manda sempre con lo stesso account... Outlook.Account senderAccount = outlook.Session.Accounts[1]; foreach (Outlook.Account account in outlook.Session.Accounts) { if (account.DisplayName == "Bidding") { senderAccount = account; } } mail.SendUsingAccount = senderAccount; mail.Subject = oggetto; mail.Body = messaggio; foreach (string dest in mailTo.Split(';')) { if (dest.Trim() != "") { mail.Recipients.Add(dest.Trim()); } } mail.CC = mailCC; //aggiungo allegato XLS foreach (string attachment in attachments) { mail.Attachments.Add(attachment); } mail.Send(); } File.Delete(excelExport); if (pathXmlOrcoExportFull != null) { //proviamo a lasciare il file come da richiesta! //File.Delete(pathXmlOrcoExportFull); } return(!interrupt); } } catch (Exception e) { Workbook.InsertLog(Core.DataBase.TipologiaLOG.LogErrore, "InvioProgrammi - Esporta.InvioMail: " + e.Message); System.Windows.Forms.MessageBox.Show(e.Message, Simboli.NomeApplicazione + " - ERRORE!!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); foreach (string file in attachments) { File.Delete(file); } return(false); } return(false); }
/// <summary> /// Send current message (MailItem) /// </summary> public void Send() { _mailitem.Send(); }
protected bool InviaMail(DefinedNames definedNames, object siglaEntita) { string fileNameFull = ""; string fileName = ""; try { fileName = @"PrevisioneGAS_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; fileNameFull = Environment.ExpandEnvironmentVariables(@"%TEMP%\" + fileName); Excel.Workbook wb = Globals.ThisWorkbook.Application.Workbooks.Add(); Workbook.Main.Range[Range.GetRange(definedNames.GetFirstRow(), definedNames.GetFirstCol(), definedNames.GetRowOffset(), definedNames.GetColOffsetRiepilogo()).ToString()].Copy(); wb.Sheets[1].Range["B2"].PasteSpecial(); wb.Sheets[1].UsedRange.ColumnWidth = 17; wb.Sheets[1].Range["A1"].Select(); wb.SaveAs(fileNameFull, Excel.XlFileFormat.xlExcel8); wb.Close(); Marshal.ReleaseComObject(wb); var config = Workbook.GetUsrConfigElement("destMailTest"); string mailTo = config.Test; string mailCC = ""; DataView entitaProprieta = new DataView(Workbook.Repository[DataBase.TAB.ENTITA_PROPRIETA]); if (Workbook.Ambiente == Simboli.PROD) { entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'PREV_CONSUMO_GAS_MAIL_TO' AND IdApplicazione = " + Workbook.IdApplicazione; if (entitaProprieta.Count > 0) { mailTo = entitaProprieta[0]["Valore"].ToString(); } entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'PREV_CONSUMO_GAS_MAIL_CC' AND IdApplicazione = " + Workbook.IdApplicazione; if (entitaProprieta.Count > 0) { mailCC = entitaProprieta[0]["Valore"].ToString(); } } if (DataBase.OpenConnection()) { Outlook.Application outlook = GetOutlookInstance(); Outlook._MailItem mail = outlook.CreateItem(Outlook.OlItemType.olMailItem); config = Workbook.GetUsrConfigElement("oggettoMail"); string oggetto = config.Value.Replace("%DATA%", DateTime.Now.ToString("dd-MM-yyyy")).Replace("%ORA%", DateTime.Now.ToString("HH:mm")); config = Workbook.GetUsrConfigElement("messaggioMail"); string messaggio = config.Value.Replace("%NOMEUTENTE%", Workbook.NomeUtente); messaggio = Regex.Replace(messaggio, @"^[^\S\r\n]+", "", RegexOptions.Multiline); ////TODO check se manda sempre con lo stesso account... Outlook.Account senderAccount = outlook.Session.Accounts[1]; foreach (Outlook.Account account in outlook.Session.Accounts) { if (account.DisplayName == "Bidding") { senderAccount = account; } } mail.SendUsingAccount = senderAccount; mail.Subject = oggetto; mail.Body = messaggio; foreach (string dest in mailTo.Split(';')) { if (dest.Trim() != "") { mail.Recipients.Add(dest.Trim()); } } mail.CC = mailCC; mail.Attachments.Add(fileNameFull); mail.Send(); File.Delete(fileNameFull); } else { string emailFolder = @"C:\Emergenza\Email\" + Simboli.NomeApplicazione; if (!Directory.Exists(emailFolder)) { Directory.CreateDirectory(emailFolder); } File.Move(fileNameFull, Path.Combine(emailFolder, fileName)); } } catch (Exception e) { Workbook.InsertLog(Core.DataBase.TipologiaLOG.LogErrore, "PrevisioneGAS.Esporta.InvioMail: " + e.Message); System.Windows.Forms.MessageBox.Show(e.Message, Simboli.NomeApplicazione + " - ERRORE!!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); if (File.Exists(fileName)) { File.Delete(fileName); } return(false); } return(true); }
/* void Send() * send a mail. */ public void Send() { //check information if (String.IsNullOrEmpty(_subject) || String.IsNullOrEmpty(_body) || _to.Count == 0) { throw new Exception("Subject, Body and To address can not be empty."); } try { //init a new mail. CreateNewMail(); //send a SMTP mail. if (_serverType == MailServerType.SMTP) { if (String.IsNullOrEmpty(_from) || String.IsNullOrEmpty(_smtpServerAddr)) { throw new Exception("From and Mail server can not be empty."); } _netMail.Subject = _subject; _netMail.From = new MailAddress(_from); //if format is HTML, we will try to get the HTML string. if (_mailType == MailType.HTML) { _netMail.Body = GetHTML(_body); } else { _netMail.Body = _body; } //add TO address _netMail.To.Clear(); foreach (string to in _to) { _netMail.To.Add(to); } //add CC address _netMail.CC.Clear(); foreach (string cc in _cc) { _netMail.CC.Add(cc); } _smtpServer.Send(_netMail); } else { #if OUTLOOK //send a outlook mail. //set title and content _oMsg.Subject = _subject; //if format is HTML, we will try to get the HTML string. if (_mailType == MailType.HTML) { _oMsg.HTMLBody = GetHTML(_body); } else { _oMsg.HTMLBody = _body; } _oRecips = (Outlook.Recipients)_oMsg.Recipients; // add each To address foreach (string to in _to) { _oRecip = (Outlook.Recipient)_oRecips.Add(to); _oRecip.Resolve(); } _oMsg.Send(); #endif } } catch (Exception ex) { throw new Exception("Can not send email: " + ex.ToString()); } finally { Clear(); } }