public SendForm(ref Mapi rma) { //editor.FormBorderStyle = FormBorderStyle.None; // 无边框 //editor.TopLevel = false; // 不是最顶层窗体 //panel1.Controls.Add(editor); // 添加到 Panel中 //editor.Show(); }
public string Query() { Mapi arret1 = new Mapi { id = "FAKE:1234", lat = 1.2345, lon = 5.4321, name = "Chateau", zone = "Oz", lines = new List <string> { "RouteDeBriqueJaunes" } }; Mapi arret2 = new Mapi { id = "FAKE:4321", lat = 2.2345, lon = 6.4321, name = "Ferme", zone = "Oz", lines = new List <string> { "RouteDeBriqueEmeraude" } }; List <Mapi> arrets = new List <Mapi> { arret1, arret2 }; return(JsonSerializer.Serialize <List <Mapi> >(arrets)); }
public void PostOrder(Mapi.Models.Order order) { foreach (var orderDetail in order.OrderDetails) { var item = genericUnitOfWork.Repository<Mapi.Models.Article>().GetById(o => o.Id == orderDetail.ItemId); orderDetail.saleTax = item.ItemCategory.SaleTax; orderDetail.importedSaleTax = item.ImportedSaleTax; } genericUnitOfWork.Repository<Mapi.Models.Order>().Insert(order); genericUnitOfWork.Save(); }
/// <summary> /// Send SimpleMAPI email /// </summary> public void SendMapi(string exceptionReport) { var mapi = new Mapi(); string emailAddress = _reportInfo.EmailReportAddress.IsEmpty() ? _reportInfo.ContactEmail : _reportInfo.EmailReportAddress; mapi.AddRecipient(emailAddress, null, false); AddMapiAttachments(mapi); mapi.Send(EmailSubject, exceptionReport, true); }
private void AddMapiAttachments(Mapi mapi) { if (_reportInfo.ScreenshotAvailable) { mapi.Attach(ScreenshotTaker.GetImageAsFile(_reportInfo.ScreenshotImage)); } foreach (string file in _reportInfo.FilesToAttach) { mapi.Attach(file); } }
private void Mail(FileInfo F) { try { Mapi mapi = new Mapi(); mapi.AddAttachment(F.FullName); mapi.SendMailPopup("MFB : " + _NomFichierSansExt, ""); } catch (Exception _Exception) { Log.Methode <ApercuAvantImpression>(); Log.Message(_Exception); } }
/// <summary> /// Resolves a recipient name using the Simple MAPI address book.</summary> /// <param name="name"> /// Recipient name to be resolved. This name may be incomplete, misspelled, or otherwise /// ambiguous.</param> /// <returns> /// A <see cref="MapiAddress"/> holding the unambiguous address book name that is the /// closest match for the specified <paramref name="name"/>, and the corresponding default /// e-mail address.</returns> /// <exception cref="ArgumentNullOrEmptyException"> /// <paramref name="name"/> is a null reference or an empty string.</exception> /// <exception cref="MapiException"> /// <see cref="Mapi.MAPIResolveName"/> indicated an error.</exception> /// <remarks><para> /// <b>ResolveName</b> determines the unambiguous address book entry of the specified /// recipient, using the Win32 API call <see cref="Mapi.MAPIResolveName"/> which is part of /// the Simple MAPI protocol. /// </para><para> /// If no match is found or the specified <paramref name="name"/> resolves to more than one /// address book entry, the user is presented with an address book dialog and asked to /// select an entry. User cancellation generates a <see cref="MapiException"/> whose <see /// cref="MapiException.Code"/> may be <see cref="MapiException.Abort"/> but also any other /// <see cref="MapiError"/> code, depending on the MAPI server. /// </para><note type="caution"> /// Non-Microsoft e-mail clients rarely support <b>MAPIResolveName</b>. Some might report an /// error while others might return empty strings or invalid data. There is no workaround /// other than using a Microsoft program as the default e-mail client.</note></remarks> public static MapiAddress ResolveName(string name) { if (String.IsNullOrEmpty(name)) { ThrowHelper.ThrowArgumentNullOrEmptyException("name"); } // remember current working directory string currentDir = Directory.GetCurrentDirectory(); // prepare recipient structure SafeMapiHandle lpRecip = null; try { // invoke MAPIResolveName to resolve this name MapiFlags flags = MapiFlags.MAPI_DIALOG | MapiFlags.MAPI_LOGON_UI; MapiError code = Mapi.MAPIResolveName(UIntPtr.Zero, UIntPtr.Zero, name, flags, 0, out lpRecip); // check for null recipient (buggy MAPI server) if (code == MapiError.SUCCESS_SUCCESS && (lpRecip == null || lpRecip.IsInvalid)) { code = MapiError.MAPI_E_FAILURE; } // throw exception if MAPI reports failure if (code != MapiError.SUCCESS_SUCCESS) { ThrowMapiException(code); } // retrieve unmanaged memory block on success MapiRecipDesc recip = (MapiRecipDesc)lpRecip.GetMemory(0, typeof(MapiRecipDesc)); // return recipient name and address return(new MapiAddress(recip.lpszName, recip.lpszAddress)); } finally { // release unmanaged memory block if (lpRecip != null) { lpRecip.Dispose(); } // restore original working directory Directory.SetCurrentDirectory(currentDir); } }
static void Main(string[] args) { // Mapi-Instanz erzeugen Mapi mapi = new Mapi(); // Logon in MAPI. Sie können den aktuellen // Benutzer einloggen, indem Sie IntPtr.Zero übergeben. // Wollen Sie einen spezifischen Benutzer einloggen, // können Sie ein Token über die API-Funktion LogonUser // erzeugen und dessen Handle übergeben. if (mapi.Logon(IntPtr.Zero) == false) { Console.WriteLine("Der Login in MAPI ist fehlgeschlagen: " + mapi.Error()); return; } // Empfänger hinzufügen string mailAddress = "*****@*****.**"; mapi.AddRecip(mailAddress, null, false); // Datei anfügen string fileName = Path.Combine(Application.StartupPath, "dontpanic.gif"); mapi.Attach(fileName); // Mail senden string subject = "Party"; string message = "Hallo Zaphod, hast du Lust auf eine Party im Restaurant " + "am Ende der Galaxis?"; if (mapi.Send(subject, message)) { Console.WriteLine("E-Mail erfolgreich versendet"); } else { Console.WriteLine("Das Senden ist fehlgeschlagen: {0}", mapi.Error()); } // Aus MAPI ausloggen mapi.Logoff(); Console.WriteLine("Beenden mit Return"); Console.ReadLine(); }
public bool PackSendImage() { try { if (_outputBitmap == null) { throw new Exception("Нет изображения"); } var fileName = Path.GetTempPath() + Guid.NewGuid() + ".bmp"; _outputBitmap.Save(fileName); var mapi = new Mapi(); mapi.AddAttachment(fileName); mapi.SendMailPopup("", ""); File.Delete(fileName); return(true); } catch (Exception exception) { XtraMessageBox.Show(exception.Message); } return(false); }
public bool UnpackSendFile() { try { if (string.IsNullOrWhiteSpace(unpackFile.RtfText)) { throw new Exception("Нет текста"); } var fileName = Path.GetTempPath() + Guid.NewGuid() + ".rtf"; using (var writer = File.CreateText(fileName)) writer.Write(unpackFile.RtfText); var mapi = new Mapi(); mapi.AddAttachment(fileName); mapi.SendMailPopup("", ""); File.Delete(fileName); return(true); } catch (Exception exception) { XtraMessageBox.Show(exception.Message); } return(false); }
private void SendMail() { try { var sb = new StringBuilder(); sb.AppendLine(BugReportResources.MessageToUser); sb.AppendLine("1. "); sb.AppendLine("2. "); sb.AppendLine("... "); sb.AppendLine(Environment.NewLine); sb.AppendLine(string.Format("{{cut {0}}}", BugReportResources.TechnicalInfo)); sb.AppendLine(BugReportResources.Separator01); //"---------------------------------------------------------" sb.AppendLine(BugReportResources.DontEditThis); //"Внимание! Не редактируйте информацию, приведенную ниже." sb.AppendLine(BugReportResources.Separator01); sb.AppendLine(string.Format("{0, -27}{1}", BugReportResources.Version, AssemblyAttributeAccessors.GetAssemblyFileVersion(Assembly.GetEntryAssembly()))); sb.AppendLine(string.Format("{0, -24}{1}", BugReportResources.DotNetVersion, Environment.Version)); sb.AppendLine(string.Format("{0, -24}{1}", BugReportResources.User, string.Concat(Environment.UserDomainName, "\\", Environment.UserName))); var machineName = Environment.MachineName; var client = WMSEnvironment.Instance.ClientCode; if (string.IsNullOrEmpty(client)) { client = machineName; } if (client != machineName) { sb.AppendLine(string.Format("{0, -24}{1}", BugReportResources.TerminalServer, machineName)); } sb.AppendLine(string.Format("{0, -35}{1}", BugReportResources.ComputerName, Environment.MachineName)); sb.AppendLine(string.Format("{0, -40}{1}", BugReportResources.OsVersion, Environment.OSVersion.VersionString)); sb.AppendLine(string.Format("{0, -30}{1}", BugReportResources.Time, DateTime.Now)); sb.AppendLine(string.Empty); if (SelectedItem != null) { sb.AppendLine(string.Format("{0}: {1}", BugReportResources.MandantCode, SelectedItem.MandantCode)); } if (StaticAdditionalParams.Count > 0) { foreach (var param in StaticAdditionalParams) { sb.AppendLine(string.Format("{0}: {1}", param.Key, param.Value)); } } if ((CurrentAdditionalParams != null) && (CurrentAdditionalParams.Count > 0)) { sb.AppendLine(string.Empty); foreach (var param in CurrentAdditionalParams) { sb.AppendLine(string.Format("{0}: {1}", param.Key, param.Value)); } } sb.AppendLine(string.Empty); sb.AppendLine(BugReportResources.ExceptionMessage).AppendLine(Message ?? string.Empty); sb.AppendLine(string.Format("{0}:{1}{2}", BugReportResources.Exception, Environment.NewLine, Exception)); sb.AppendLine("{cut}"); Mapi.SendMail( HelpServiceMail, string.Empty, string.Format(ErrorMessageSubjectTemplate, AssemblyAttributeAccessors.AssemblyProduct), sb.ToString(), Attachments, true); } catch (Exception ex) { Close(); //ShowError("Невозможно отправить письмо в службу технической поддержки", ex, false); ShowError(message: BugReportResources.UnableSendEmailToSupport, ex: ex, additionalParams: null, attachments: null, isBtnSandMailEnable: false, mandantCode: SelectedItem == null ? null : SelectedItem.MandantCode); } }
/// <summary> /// Writes all the properties that are part of the <see cref="Appointment"/> object either as <see cref="CFStorage"/>'s /// or <see cref="CFStream"/>'s to the <see cref="CompoundFile.RootStorage"/> /// </summary> private void WriteToStorage() { var rootStorage = CompoundFile.RootStorage; long messageSize = 0; messageSize += Recipients.WriteToStorage(rootStorage); messageSize += Attachments.WriteToStorage(rootStorage); var recipientCount = Recipients.Count; var attachmentCount = Attachments.Count; var propertiesStream = new TopLevelProperties(recipientCount, attachmentCount, recipientCount, attachmentCount); if (!string.IsNullOrEmpty(InternetMessageId)) { propertiesStream.AddProperty(PropertyTags.PR_INTERNET_MESSAGE_ID_W, InternetMessageId); } propertiesStream.AddProperty(PropertyTags.PR_ENTRYID, Mapi.GenerateEntryId()); propertiesStream.AddProperty(PropertyTags.PR_INSTANCE_KEY, Mapi.GenerateInstanceKey()); propertiesStream.AddProperty(PropertyTags.PR_STORE_SUPPORT_MASK, StoreSupportMaskConst.StoreSupportMask, PropertyFlags.PROPATTR_READABLE); propertiesStream.AddProperty(PropertyTags.PR_STORE_UNICODE_MASK, StoreSupportMaskConst.StoreSupportMask, PropertyFlags.PROPATTR_READABLE); propertiesStream.AddProperty(PropertyTags.PR_ALTERNATE_RECIPIENT_ALLOWED, true, PropertyFlags.PROPATTR_READABLE); propertiesStream.AddProperty(PropertyTags.PR_HASATTACH, attachmentCount > 0); var messageFlags = MessageFlags.MSGFLAG_UNMODIFIED; if (Draft) { messageFlags |= MessageFlags.MSGFLAG_UNSENT | MessageFlags.MSGFLAG_FROMME; IconIndex = MessageIconIndex.UnsentMail; } if (attachmentCount > 0) { messageFlags |= MessageFlags.MSGFLAG_HASATTACH; } if (!SentOn.HasValue) { SentOn = DateTime.UtcNow; } propertiesStream.AddProperty(PropertyTags.PR_CLIENT_SUBMIT_TIME, SentOn); propertiesStream.AddProperty(PropertyTags.PR_MESSAGE_FLAGS, messageFlags); propertiesStream.AddProperty(PropertyTags.PR_ACCESS, MapiAccess.MAPI_ACCESS_DELETE | MapiAccess.MAPI_ACCESS_MODIFY | MapiAccess.MAPI_ACCESS_READ); propertiesStream.AddProperty(PropertyTags.PR_ACCESS_LEVEL, MapiAccess.MAPI_ACCESS_MODIFY); propertiesStream.AddProperty(PropertyTags.PR_OBJECT_TYPE, MapiObjectType.MAPI_MESSAGE); SetSubject(); propertiesStream.AddProperty(PropertyTags.PR_SUBJECT_W, Subject); propertiesStream.AddProperty(PropertyTags.PR_NORMALIZED_SUBJECT_W, SubjectNormalized); propertiesStream.AddProperty(PropertyTags.PR_SUBJECT_PREFIX_W, SubjectPrefix); propertiesStream.AddProperty(PropertyTags.PR_CONVERSATION_TOPIC_W, SubjectNormalized); // http://www.meridiandiscovery.com/how-to/e-mail-conversation-index-metadata-computer-forensics/ // http://stackoverflow.com/questions/11860540/does-outlook-embed-a-messageid-or-equivalent-in-its-email-elements //propertiesStream.AddProperty(PropertyTags.PR_CONVERSATION_INDEX, Subject); // TODO: Change modification time when this message is opened and only modified var utcNow = DateTime.UtcNow; propertiesStream.AddProperty(PropertyTags.PR_CREATION_TIME, utcNow); propertiesStream.AddProperty(PropertyTags.PR_LAST_MODIFICATION_TIME, utcNow); propertiesStream.AddProperty(PropertyTags.PR_MESSAGE_CLASS_W, "IPM.Appointment"); propertiesStream.AddProperty(PropertyTags.PR_PRIORITY, Priority); propertiesStream.AddProperty(PropertyTags.PR_IMPORTANCE, Importance); propertiesStream.AddProperty(PropertyTags.PR_MESSAGE_LOCALE_ID, CultureInfo.CurrentCulture.LCID); propertiesStream.AddProperty(PropertyTags.PR_ICON_INDEX, IconIndex); if (Sender != null) { Sender.WriteProperties(propertiesStream); } if (Receiving != null) { Receiving.WriteProperties(propertiesStream); } if (Representing != null) { Representing.WriteProperties(propertiesStream); } if (ReceivingRepresenting != null) { ReceivingRepresenting.WriteProperties(propertiesStream); } if (recipientCount > 0) { var displayTo = new List <string>(); var displayCc = new List <string>(); var displayBcc = new List <string>(); foreach (var recipient in Recipients) { switch (recipient.RecipientType) { case RecipientType.To: if (!string.IsNullOrWhiteSpace(recipient.DisplayName)) { displayTo.Add(recipient.DisplayName); } else if (!string.IsNullOrWhiteSpace(recipient.Email)) { displayTo.Add(recipient.Email); } break; case RecipientType.Cc: if (!string.IsNullOrWhiteSpace(recipient.DisplayName)) { displayCc.Add(recipient.DisplayName); } else if (!string.IsNullOrWhiteSpace(recipient.Email)) { displayCc.Add(recipient.Email); } break; case RecipientType.Bcc: if (!string.IsNullOrWhiteSpace(recipient.DisplayName)) { displayBcc.Add(recipient.DisplayName); } else if (!string.IsNullOrWhiteSpace(recipient.Email)) { displayBcc.Add(recipient.Email); } break; default: throw new ArgumentOutOfRangeException(); } } propertiesStream.AddProperty(PropertyTags.PR_DISPLAY_TO_W, string.Join(";", displayTo), PropertyFlags.PROPATTR_READABLE); propertiesStream.AddProperty(PropertyTags.PR_DISPLAY_CC_W, string.Join(";", displayCc), PropertyFlags.PROPATTR_READABLE); propertiesStream.AddProperty(PropertyTags.PR_DISPLAY_BCC_W, string.Join(";", displayBcc), PropertyFlags.PROPATTR_READABLE); } propertiesStream.AddProperty(PropertyTags.PR_INTERNET_CPID, Encoding.UTF8.CodePage); if (BodyRtfCompressed) { propertiesStream.AddProperty(PropertyTags.PR_RTF_COMPRESSED, RTFCompressor.Compress(Encoding.ASCII.GetBytes(BodyRtf))); propertiesStream.AddProperty(PropertyTags.PR_RTF_IN_SYNC, true); } var namedProperties = new NamedProperties(propertiesStream); //Uses the top level properties. namedProperties.AddProperty(NamedPropertyTags.PidLidLocation, Location); namedProperties.AddProperty(NamedPropertyTags.PidLidAppointmentStartWhole, MeetingStart); namedProperties.AddProperty(NamedPropertyTags.PidLidAppointmentEndWhole, MeetingEnd); namedProperties.AddProperty(NamedPropertyTags.PidLidMeetingType, MeetingType.mtgRequest); namedProperties.AddProperty(NamedPropertyTags.PidLidAppointmentSubType, AllDay); namedProperties.AddProperty(NamedPropertyTags.PidLidAppointmentStateFlags, AppointmentState.asfMeeting); namedProperties.WriteProperties(rootStorage); propertiesStream.WriteProperties(rootStorage, messageSize); }
public SendForm(Form callingForm, ref Mapi rma) { ma = rma; oNS = oApp.GetNamespace("mapi"); oNS.Logon(Missing.Value, Missing.Value, true, true); oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); preForm = callingForm as Form3; ma.Reset(); InitializeComponent(); Form1.unitTB[] unitsTB = preForm.returnUnitTB(); Form1.unitInfo[] unitInfos = preForm.returnUnitInfo(); if (preForm.returnChoose() == 1) { //textTO.Text = "Lee, Simon <*****@*****.**>; Hsu, Aurora <*****@*****.**>; HUNG, SEAN (Sean Hung) <*****@*****.**>; Tsai, Hunter <*****@*****.**>; Hsieh, David (David Hsieh) <*****@*****.**>; Chou, Cindy <*****@*****.**>; Cheng, Steven <*****@*****.**>; Su, Demi <*****@*****.**>; Chen, Frank (COMMs TDC) <*****@*****.**>; Su, YJ <*****@*****.**>; Lee, Connant <*****@*****.**>; Tseng, YJ <*****@*****.**>; Wu, Jason <*****@*****.**>; Lin, Robin ((COMM TDC)) <*****@*****.**>; Yang, Daniel (Comm TDC) <*****@*****.**>; Chen, Pat <*****@*****.**>; Lin, CF <*****@*****.**>; Chen, Troy (CMIT NB RandD) <*****@*****.**>; Hung, KC <*****@*****.**>; Lu, Jacky <*****@*****.**>; Chiang, Bernice <*****@*****.**>; Chan, Tony (WWAN) <*****@*****.**>; Lee, Amanda <*****@*****.**>; Chan, Tony (WWAN) <*****@*****.**>; Chien, Jeremy (Comms Radio HW) <*****@*****.**>; Chou, Emily (CMIT) <*****@*****.**>; Wu, Kent <*****@*****.**>; Chen, Xinchang (Comm TDC) <*****@*****.**>; Ma, Terry <*****@*****.**>; Lin, Steve <*****@*****.**>; Wu, Anthony <*****@*****.**>; Chou, Emily (CMIT) <*****@*****.**>; Cheng, Timothy <*****@*****.**>; Liu, Bruce <*****@*****.**>; Huang, Jake <*****@*****.**>; Tung, Grace <*****@*****.**>; Kuo, Jason <*****@*****.**>; You, Ethan (Comm TDC) <*****@*****.**>; Zeng, Grey <*****@*****.**>; Fong, Agness <*****@*****.**>; Liu, Sean (Comm TDC) <*****@*****.**>; Yu, Debby <*****@*****.**>; Hsieh, Sean <*****@*****.**>; Hsieh, James <*****@*****.**>; Lin, Tony <*****@*****.**>; Tsai, David <*****@*****.**>; Cheng, Mike <*****@*****.**>; Chu, Jimmy <*****@*****.**>"; //textCC.Text = "Chang, Hans <*****@*****.**>; Hung, KC <*****@*****.**>; Cheng, Steven <*****@*****.**>"; textSubject.Text = "Machines arrived "; Array.Clear(ph, 0, ph.Length); //if (ph.Length != 0) //{ // Array.Resize(ref ph, 0); //} bool phExist = false; for (int j = 0; j < unitsTB.Length; j++) { for (int i = 0; i < ph.Length; i++) { if (unitsTB[j].platform == ph[i]) { phExist = true; } } if (phExist == false) { Array.Resize(ref ph, ph.Length + 1); ph[ph.Length - 1] = unitsTB[j].platform; } phExist = false; } for (int i = 0; i < ph.Length; i++) { if (ph[i] != null) { textSubject.Text += "【" + ph[i] + "】"; } } sHtml += num1_start; createTable("CNB"); createTable("BNB"); createTable("CDT"); createTable("BDT"); createTable("CAIO"); createTable("BAIO"); sHtml += num1_endMail; } else { textSubject.Text = "IUR record update"; sHtml = num2_start + num1_type_open; if (unitInfos[0].Borrower == "Storage" || unitInfos[0].Borrower == "storage") { sHtml += "Return list"; } else { sHtml += "Borrow list"; } sHtml += num1_type_close + num2_table_open; for (int i = 0; i < unitInfos.Length; i++) { sHtml += num2_rowOpen1 + (i + 1).ToString() + "\">" + num2_rowOpen2 + unitInfos[i].Platform.ToString() + num2_rowClose + num2_rowOpen2 + unitInfos[i].Phase.ToString() + num2_rowClose + num2_rowOpen2 + unitInfos[i].SKU.ToString() + num2_rowClose + num2_rowOpen2_col4 + unitInfos[i].SN.ToString() + num2_rowClose + num2_rowOpen2_col5 + unitInfos[i].Borrower.ToString() + num2_rowClose + num2_rowOpen2 + unitInfos[i].Status.ToString() + num2_rowClose + num2_rowOpen2 + unitInfos[i].Year.ToString() + num2_rowClose + num2_rowOpen2 + unitInfos[i].Category.ToString() + num2_rowClose + num2_rowOpen2 + unitInfos[i].Note.ToString() + num2_rowClose + num2_rowOpen2 + unitInfos[i].Date.Substring(0, 10).ToString() + num2_rowClose + "</TR>"; } sHtml += "</TBODY></TABLE></SPAN></P>" + num1_endMail; //string htmltext = editor1.Html.ToString(); //System.IO.File.WriteAllText(@"C:\Users\HP\Desktop\htmltext.txt", htmltext); } editor1.Html = sHtml; //System.IO.File.WriteAllText(@"C:\Users\HP\Desktop\htmltext.txt", editor1.Html); }
public void PostItem(Mapi.Models.Article item) { genericUnitOfWork.Repository<Mapi.Models.Article>().Insert(item); genericUnitOfWork.Save(); }
/// <summary> /// Allows the user to select recipients from the Simple MAPI address book.</summary> /// <returns> /// An <see cref="Array"/> of <see cref="MapiAddress"/> instances holding the selected /// address book names and the corresponding e-mail addresses.</returns> /// <exception cref="MapiException"> /// <see cref="Mapi.MAPIAddress"/> indicated an error.</exception> /// <remarks><para> /// <b>Address</b> shows a dialog allowing the user to select e-mail recipients from an /// address book, using the Win32 API call <see cref="Mapi.MAPIAddress"/> which is part of /// the Simple MAPI protocol. Only the "To" recipient type is available. /// </para><para> /// <b>Address</b> returns an empty array if the user cancelled the dialog or did not select /// any recipients. No <see cref="MapiException"/> is generated in this case. /// </para><note type="caution"> /// <para>Non-Microsoft e-mail clients rarely support <b>MAPIAddress</b>. Some might report /// an error while others might show a nonfunctional dialog or return invalid data. There is /// no workaround other than using a Microsoft program as the default e-mail client. /// </para><para> /// Also note that Simple MAPI does not specify the order in which <b>MAPIAddress</b> /// returns the selected recipients. <b>Address</b> maintains the selection order for /// Outlook Express, but the order may be reversed or completely arbitrary for other e-mail /// clients.</para></note></remarks> public static MapiAddress[] Address() { // remember current working directory string currentDir = Directory.GetCurrentDirectory(); // prepare recipient list data uint nNewRecips = 0; SafeMapiHandle lpNewRecips = null; try { // invoke MAPIAddress to create a recipient list MapiFlags flags = MapiFlags.MAPI_LOGON_UI; MapiError code = Mapi.MAPIAddress(UIntPtr.Zero, UIntPtr.Zero, null, 1, null, 0, IntPtr.Zero, flags, 0, out nNewRecips, out lpNewRecips); // check for user cancellation if (code == MapiError.MAPI_E_USER_ABORT) { return(new MapiAddress[0]); } // check for null recipient list (buggy MAPI server) if (code == MapiError.SUCCESS_SUCCESS && nNewRecips > 0 && (lpNewRecips == null || lpNewRecips.IsInvalid)) { code = MapiError.MAPI_E_FAILURE; } // throw exception if MAPI reports failure if (code != MapiError.SUCCESS_SUCCESS) { ThrowMapiException(code); } // create (possibly empty) output recipient array MapiAddress[] entries = new MapiAddress[nNewRecips]; if (nNewRecips == 0) { return(entries); } // prepare managed recipient object int size = Marshal.SizeOf(typeof(MapiRecipDesc)); MapiRecipDesc recip = new MapiRecipDesc(); // retrieve unmanaged memory blocks for (int i = 0; i < nNewRecips; i++) { // copy current array element to managed memory lpNewRecips.GetMemory(i * size, recip); // HACK: Outlook Express inverts the order of selected entries. // We re-invert the order since OE is the most likely client. int index = (int)(nNewRecips - i - 1); // store entry name and address entries[index] = new MapiAddress(recip.lpszName, recip.lpszAddress); } return(entries); } finally { // release unmanaged memory block if (lpNewRecips != null) { lpNewRecips.Dispose(); } // restore original working directory Directory.SetCurrentDirectory(currentDir); } }
/// <summary> /// Creates and sends an e-mail message using the Simple MAPI protocol.</summary> /// <param name="subject"> /// The subject line of the e-mail message.</param> /// <param name="noteText"> /// The text of the e-mail message.</param> /// <param name="recipients"> /// An <see cref="Array"/> of <see cref="MapiAddress"/> instances holding the display names /// and SMTP addresses of all message recipients. The protocol identifier "smtp:" is /// automatically prepended to any non-empty addresses without this prefix.</param> /// <param name="attachments"> /// An <see cref="Array"/> of <see cref="MapiAddress"/> instances holding the display names /// and fully qualified local file paths of any attachment files sent to the <paramref /// name="recipients"/>.</param> /// <exception cref="MapiException"> /// <see cref="Mapi.MAPISendMail"/> indicated an error.</exception> /// <remarks><para> /// <b>SendMail</b> creates and sends an e-mail message with optional file attachments, /// using the Win32 API call <see cref="Mapi.MAPISendMail"/> which is part of the Simple /// MAPI protocol. The originator is left undefined which will cause Simple MAPI to assert /// the user’s default e-mail account as the originator. /// </para><para> /// The <paramref name="subject"/> and <paramref name="noteText"/> parameters may be a null /// reference or an empty string to leave the corresponding field blank. The <paramref /// name="recipients"/> and <paramref name="attachments"/> parameters may be null references /// or empty arrays to create a message without recipients or file attachments, /// respectively. /// </para><para> /// The e-mail message is presented to the user who can choose to edit (filling in any blank /// fields or adding text as desired), send, or cancel the message. User cancellation /// generates a <see cref="MapiException"/> whose <see cref="MapiException.Code"/> is <see /// cref="MapiException.Abort"/>.</para></remarks> public static void SendMail(string subject, string noteText, MapiAddress[] recipients, MapiAddress[] attachments) { // remember current working directory string currentDir = Directory.GetCurrentDirectory(); // construct MAPI message descriptor MapiMessage message = new MapiMessage(); message.lpszSubject = subject; message.lpszNoteText = noteText; try { // create any specified recipients if (recipients != null && recipients.Length > 0) { // store count of recipient descriptors int count = recipients.Length; message.nRecipCount = (uint)count; // allocate memory for recipient descriptors int size = Marshal.SizeOf(typeof(MapiRecipDesc)); message.lpRecips.AllocateHandle(count * size); // construct recipient descriptors MapiRecipDesc recip = new MapiRecipDesc(); for (int i = 0; i < count; i++) { // prepend "smtp:" to address if not present string address = recipients[i].Address; if (!String.IsNullOrEmpty(address) && !address.StartsWith("smtp:", StringComparison.OrdinalIgnoreCase)) { address = "smtp:" + address; } // create MAPI recipient descriptor recip.ulRecipClass = MapiRecipClass.MAPI_TO; recip.lpszName = recipients[i].Name; recip.lpszAddress = address; // copy recipient descriptor to unmanaged memory message.lpRecips.SetMemory(recip, i * size, false); } } // create any specified attachments if (attachments != null && attachments.Length > 0) { // store count of attachment descriptors int count = attachments.Length; message.nFileCount = (uint)count; // allocate memory for attachment descriptors int size = Marshal.SizeOf(typeof(MapiFileDesc)); message.lpFiles.AllocateHandle(count * size); // construct attachment descriptors MapiFileDesc fileDesc = new MapiFileDesc(); for (int i = 0; i < count; i++) { // create MAPI file attachment descriptor fileDesc.lpszFileName = attachments[i].Name; fileDesc.lpszPathName = attachments[i].Address; fileDesc.nPosition = 0xffffffff; // don’t embed files // copy attachment descriptor to unmanaged memory message.lpFiles.SetMemory(fileDesc, i * size, false); } } // invoke MAPISendMail to deliver this message MapiFlags flags = MapiFlags.MAPI_DIALOG | MapiFlags.MAPI_LOGON_UI; MapiError code = Mapi.MAPISendMail(UIntPtr.Zero, UIntPtr.Zero, message, flags, 0); // throw exception if MAPI reports failure if (code != MapiError.SUCCESS_SUCCESS) { ThrowMapiException(code); } } finally { // release unmanaged memory blocks message.Dispose(); // restore original working directory Directory.SetCurrentDirectory(currentDir); } }