Send Email Marked High Importance via EWS API - c#

Attempting to send an email marked as high importance via EWS API. Getting multiple compile errors and or issues stating missing assembly. Any help would be appreciated. Using the following namespaces:
System
System.Drawing
System.Data
Microsoft.Exchange.WebServices.Data
System.Collections.Generic
System.Web
System.Text
System.IO
System.Linq
I've referenced all the MS Docs on the EWS API and aware that the importance is an enum but unsure of the class to use to set the argument;
https://learn.microsoft.com/en-us/dotnet/api/microsoft.exchange.webservices.data?view=exchange-ews-api
https://learn.microsoft.com/en-us/previous-versions/office/exchange-server-api/aa564670(v=exchg.150)
https://learn.microsoft.com/en-us/dotnet/api/microsoft.exchange.webservices.data.importance?view=exchange-ews-api
I've tried multiple bits of syntax e.g. email.Importance = 2 but getting enum conversion error.
Current code is as follows:
Success = true;
ErrorMessage = "";
try {
if (To == "" && CC == "" && BCC == "") {
throw new Exception("Recipients was not provided");
}
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
string serviceUrl = "https://mail.mydomain.com/ews/exchange.asmx";
service.Url = new Uri(serviceUrl);
EmailMessage email = new EmailMessage(service);
email.Subject = Subject;
if (isHTML) {
email.Body = new MessageBody(BodyType.HTML, Message);
} else {
email.Body = new MessageBody(BodyType.Text, Message);
}
if (isHighImportance) {
email.Importance = new ImportantChoiceType(HIGH);
} else {
email.Importance = new ImportantChoiceType(NORMAL);
}
char[] splitComma = new char[]{','};
char[] splitAsterisk = new char[]{'*'};
char[] splitSemicolon = new char[]{';'};
char[] splitAny = new char[]{',',';'};
//To
foreach (String r in To.Split(splitAny, StringSplitOptions.RemoveEmptyEntries))
{
email.ToRecipients.Add(r.Trim());
}
//CC
foreach (String r in CC.Split(splitAny, StringSplitOptions.RemoveEmptyEntries))
{
email.CcRecipients.Add(r.Trim());
}
//BCC
foreach (String r in BCC.Split(splitAny, StringSplitOptions.RemoveEmptyEntries))
{
email.BccRecipients.Add(r.Trim());
}
//SaveDraft
email.Save(SearchFolderByName(service,"Drafts",mailbox));
// Add attachments
foreach (String att in Attachments.Split(splitSemicolon, StringSplitOptions.RemoveEmptyEntries))
{
if (att.Contains(new string(splitAsterisk))) {
String[] attArray = att.Split(splitAsterisk, StringSplitOptions.RemoveEmptyEntries);
FileAttachment fileatt = email.Attachments.AddFileAttachment(attArray[0]);
fileatt.IsInline = true;
fileatt.ContentId = attArray[1];
} else {
email.Attachments.AddFileAttachment(att);
}
}
//Send
if (SaveSent)
{
email.SendAndSaveCopy(SearchFolderByName(service,"SentItems",mailbox));
} else {
email.Send();
}
}
catch (Exception e)
{
Success = false;
ErrorMessage = e.ToString();
}

Importance property in EmailMessage class is Enum so you have to use importance enum.
email.Importance = Importance.High // Or Importance.Low or Importance.Normal

Related

Sendgrid dynamic data not being sent to Template

This is how I send my email:
public async System.Threading.Tasks.Task<string> SendInternalEmail(BasicEmailStructureViewModel Structure, List<string> AdditionalVariables, TenantEmailTemplate tenantEmailTemplate, TenantCommunication tenantCommunication, string ReceiverId, string ReceiverEmail, string ReceiverName, string CampaignName)
{
try
{
var client = new SendGridClient(tenantCommunication.SendgridApiKey);
var message = new SendGridMessage();
message.SetFrom(new EmailAddress(tenantCommunication.SendgridPrimarySender, tenantCommunication.SendgridPrimarySenderTag));
message.AddTo(new EmailAddress(ReceiverEmail, $"{ReceiverName}"));
message.Subject = tenantEmailTemplate.Subject;
message.SetTemplateId(tenantEmailTemplate.TemplateId);
List<string> jsonVars = new List<string>();
var subjectString = #$"""subject"":""{tenantEmailTemplate.Subject}""";
jsonVars.Add(subjectString);
foreach (PropertyInfo prop in Structure.GetType().GetProperties())
{
var variableString = #$"""{prop.Name}"":""{prop.GetValue(Structure, null)}""";
}
for (var i = 0; i < AdditionalVariables.Count; i++)
{
jsonVars.Add(AdditionalVariables[i]);
}
var flattenList = "{" + string.Join(",", jsonVars) + "}";
var emailData = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(flattenList);
message.SetTemplateData(emailData);
if (CampaignName != null && CampaignName != "")
{
message.AddCustomArg("CampaignName", CampaignName);
}
var response = await client.SendEmailAsync(message);
if (response.IsSuccessStatusCode == true)
{
return Guid.NewGuid().ToString();
}
else
{
var errorMessage = response.Body.ReadAsStringAsync().Result;
return errorMessage;
}
}
catch(Exception e)
{
if (e != null)
{
return e.Message;
}
}
return "Invalid Email";
}
A typical input to this function will be like this:
var variableString =
#$"""verification_link"":""www.website.com?Key={Input.Key}""";
My email sends normally, however, none of the variables that I have set have been sent through. This is based roughly off the template sample on github: https://github.com/sendgrid/sendgrid-csharp/blob/main/examples/templates/templates.cs
Is there another sample I can use or what is the correct way to send variables dynamically?
I don't think that is the best way to construct the JSON for your dynamic template variables.
Would it be possible for you to build the variables as an object and then serialize them. Like:
var templateData = new {
subject = tenantEmailTemplate.Subjectm
otherVariableName = otherVariable
};
string emailData = JsonConvert.SerializeObject(templateData);
message.SetTemplateData(emailData);

MailItem attachment unknown

I have a mail containing only a signature as an image and an attachment like the screenshot below.
I save this email as C:\mail.msg, I try then to read it by the code below:
var oApp = new Microsoft.Office.Interop.Outlook.Application();
MailItem outlookMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItemFromTemplate(#"C:\mail.msg");
//there are 2 attachments inside
foreach(var att in outlookMsg.Attachments)
{
att.SaveAsFile($#"C:\{att.FileName}");
}
The problem
There are 2 attachments inside the MailItem named :
-empty.xlsx
-lot4.xlsx
If I change the extension of lot4.xlsx to lot4.png, it can be opened as the image in the signature.
Someone has seen this strange situation when an attachment is added with name incorrect?
You could download attachments using the below code:
private void ThisApplication_NewMail()
{
Outlook.MAPIFolder inBox = this.Application.ActiveExplorer()
.Session.GetDefaultFolder(Outlook
.OlDefaultFolders.olFolderInbox);
Outlook.Items inBoxItems = inBox.Items;
Outlook.MailItem newEmail = null;
inBoxItems = inBoxItems.Restrict("[Unread] = true");
try
{
foreach (object collectionItem in inBoxItems)
{
newEmail = collectionItem as Outlook.MailItem;
if (newEmail != null)
{
if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail
.Attachments.Count; i++)
{
newEmail.Attachments[i].SaveAsFile
(#"C:\TestFileSave\" +
newEmail.Attachments[i].FileName);
}
}
}
}
}
catch (Exception ex)
{
string errorInfo = (string)ex.Message
.Substring(0, 11);
if (errorInfo == "Cannot save")
{
MessageBox.Show(#"Create Folder C:\TestFileSave");
}
}
}
For more information, please refer to this link:
How to: Programmatically save attachments from Outlook email items
With Microsoft EWS, its very easy to do:
reference: http://johnlabtest.blogspot.com/2014/01/save-attachments-from-exchange-mail-box.html
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("user1#contoso.com", "password");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("user1#contoso.com", RedirectionUrlValidationCallback);
var messages = new List<EmailMessage>();
// only get unread emails
SearchFilter folderSearchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
// we just need the id in our results
var itemView = new ItemView(10) {PropertySet = new PropertySet(BasePropertySet.IdOnly)};
FindItemsResults<Item> findResults = service.FindItems(folder.Id, folderSearchFilter, itemView);
foreach (Item item in findResults.Items.Where(i => i is EmailMessage))
{
EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
messages.Add(message);
}
// loop through messages and call processemail here.
}
public static void ProcessEmail(EmailMessage message)
{
string saveDir = ConfigurationManager.AppSettings["AttachmentSaveDirectory"];
if (message.HasAttachments)
{
foreach (Attachment attachment in message.Attachments.Where(a=> a is FileAttachment))
{
FileAttachment fileAttachment = attachment as FileAttachment;
fileAttachment.Load(); // populate the content property of the attachment
using (FileStream fs = new FileStream(saveDir + attachment.Name, FileMode.Create))
{
using (BinaryWriter w = new BinaryWriter(fs))
{
w.Write(fileAttachment.Content);
}
}
}
}
message.IsRead = true;
message.Update(ConflictResolutionMode.AutoResolve); // push changes back to server
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}

Reading Multiple Outlook Email for multiple IDs in C#

Referring to the answer mentioned in the post:
Reading Outlook Mail with C#
This code works well for a single account, but the issue with the current code is that it reads the email of the default id which was set as the first one in the outlook app.
For example, if "abcxyz#outlook.com" is set as the first account and "decxyz#outlook.com" is set as the second one, then it reads the inbox of only the first id, i.e., "abcxyz#outlook.com". I tried doing some modifications in the code but it did not work. Below is my code:
public static void OutLookMailStart(string EmailID, string password)
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
Microsoft.Office.Interop.Outlook.MailItem mailItem = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(EmailID, password, false, true);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
foreach (Object mail in inboxFolder.Items)
{
if ((mail as MailItem) != null && (mail as MailItem).UnRead == true)
{
// Email Subject
string Subject = (mail as MailItem).Subject.ToString();
if (Subject.Contains(FileDomain))
{
// Email Body
var ReplyText = ExtractReply(((mail as MailItem).Body.ToString()), FromTrimName);
}
// (mail as MailItem).UnRead = false;
(mail as MailItem).Save();
}
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ns.Logoff();
inboxFolder = null;
subFolder = null;
mailItem = null;
app = null;
}}
Any sort of help will be appreciated.
public static void OutLookMailStart(string EmailID, string password)
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
Microsoft.Office.Interop.Outlook.MailItem mailItem = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(EmailID, password, true, true);
inboxFolder = ns.Folders[EmailID].Folders[2];
foreach (Microsoft.Office.Interop.Outlook.MailItem mailItemm in inboxFolder.Items)
{
if (mailItemm.UnRead) // I only process the mail if unread
{
// Email Subject
Console.WriteLine("Subject : {0}", mailItemm.Subject);
string Subject = mailItemm.Subject;
if (!string.IsNullOrEmpty(Subject) && !string.IsNullOrWhiteSpace(Subject))
{
if (Subject.Contains(FileDomain))
{
var SenderName = mailItemm.Sender.Name;
//Email Body
Console.WriteLine("Accounts: {0}", mailItemm.Body);
// Read All Attachements
var attachments = (mailItemm as MailItem).Attachments;
if (attachments != null && attachments.Count > 0)
{
for (int i = 1; i <= attachments.Count; i++)
{
attachments[i].SaveAsFile(tempFolderPath + (mailItemm as MailItem).Attachments[i].FileName);
}
}
}
}
}
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ns.Logoff();
inboxFolder = null;
subFolder = null;
mailItem = null;
app = null;
}
}
Using ExchangeService service
public static void Cloud_OutLookMailStart(string EmailID, string password, string StoreFilePath)
{
try
{
LogHelper.LogMessage("<----- Cloud_OutLookMailStart Start ----->");
DistributionReplyEntity ObjDistributionReplyEntity = new DistributionReplyEntity();
ObjDistributionReplyEntity.OutLookEmailID = EmailID;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new WebCredentials(EmailID, password);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
//service.Url = new Uri("https://IP/EWS/Exchange.asmx");
service.AutodiscoverUrl(EmailID, RedirectionUrlValidationCallback);
Microsoft.Exchange.WebServices.Data.Folder inbox = Microsoft.Exchange.WebServices.Data.Folder.Bind(service, WellKnownFolderName.Inbox);
var items = service.FindItems(
//Find Mails from Inbox of the given Mailbox
new FolderId(WellKnownFolderName.Inbox, new Mailbox(EmailID)),
//Filter criterion
// new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter[] {
// new SearchFilter.ContainsSubstring(ItemSchema.Subject, ConfigurationManager.AppSettings["ValidEmailIdentifier"].ToString()),
new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false),
// }),
//View Size as 15
new ItemView(50));
Console.WriteLine("Email {0}, unread Total Count{1}", EmailID, items.Count());
foreach (Item item in items)
{
EmailMessage email = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId.ToString()));
if (!string.IsNullOrEmpty(email.Subject) && !string.IsNullOrWhiteSpace(email.Subject))
{
var subject = email.Subject.ToString();
String[] arr = subject.Split(' ');
String firstWord = arr[0];
if (firstWord != "Undeliverable:")
{
//PROCESS EMAIL MESSAGE
Console.WriteLine("Subject :{0}", email.Subject);
// TO
if (email.ToRecipients.Count > 0)
{
var propertySet = new PropertySet(ItemSchema.UniqueBody);
EmailMessage email2 = EmailMessage.Bind(service, email.Id, propertySet);
EmailMessage str = (EmailMessage)email2;
string str1 = str.UniqueBody.Text.ToString();
var EmailBody = ExtractReply(str1, "");
// string ReceiverEmail = email.ReceivedBy != null?email.ReceivedBy.Address:"" ;
// Email Body
// var subjectEmail = ExtractReply(email.Body.ToString(), email.ReceivedBy.Address);
Console.WriteLine("Body {0}", EmailBody.ToString()); // Body
ObjDistributionReplyEntity.EmailBody = EmailBody;
string maltipleTo = string.Empty;
foreach (var toemailid in email.ToRecipients)
{
if (string.IsNullOrEmpty(maltipleTo))
{
maltipleTo = toemailid.Address.ToString();
}
else
{
maltipleTo += ";" + toemailid.Address.ToString();
}
}
Console.WriteLine("TO {0}", maltipleTo.ToString()); // TO
ObjDistributionReplyEntity.ReplyTO = maltipleTo.ToString();
}
// CC
if (email.CcRecipients.Count > 0)
{
string maltipleCC = string.Empty;
foreach (var ccemailid in email.CcRecipients)
{
if (string.IsNullOrEmpty(maltipleCC))
{
maltipleCC = ccemailid.Address.ToString();
}
else
{
maltipleCC += ";" + ccemailid.Address.ToString();
}
}
Console.WriteLine("CC {0}", maltipleCC.ToString());
ObjDistributionReplyEntity.ReplyCC = maltipleCC.ToString();
}
// Form
if (email.Sender.Address != "")
{
ObjDistributionReplyEntity.ReplyForm = email.Sender.Address;
}
Console.WriteLine("Subject {0}", email.Subject.ToString()); // Subject
ObjDistributionReplyEntity.Subject = email.Subject.ToString();
ObjDistributionReplyEntity.TransactionsID = 0;
ObjDistributionReplyEntity.IsProjectRelated = 0;
string Subject = email.Subject;
ObjDistributionReplyEntity.ReceivedTime = email.DateTimeReceived;
var getSharePointFileUrl = GetAttachmentsFromEmail(service, item.Id, StoreFilePath, ObjDistributionReplyEntity.TransactionsID);
email.IsRead = true;
email.Update(ConflictResolutionMode.AlwaysOverwrite);
}
}
}
LogHelper.LogMessage("<----- Cloud_OutLookMailStart Start ----->");
}
catch (Exception ex)
{
LogHelper.LogError("OutLookMailStart -> Cloud_OutLookMailStart Exception");
LogHelper.LogError("Exception Message :" + ex.Message);
if (ex.InnerException != null)
{
LogHelper.LogError("Exception InnerException :" + ex.InnerException);
}
LogHelper.LogError("Exception StackTrace :" + ex.StackTrace);
LogHelper.LogError("OutLookMailStart -> Cloud_OutLookMailStart Exception");
}
}
public static string GetAttachmentsFromEmail(ExchangeService service, ItemId itemId, string StoreFilePath, Int64 TransactionsID)
{
try
{
LogHelper.LogMessage("<----- GetAttachmentsFromEmail Start ----->");
// Bind to an existing message item and retrieve the attachments collection.
// This method results in an GetItem call to EWS.
EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(ItemSchema.Attachments));
List<ResponseMessage> ObjResponseMessage = new List<ResponseMessage>();
// Iterate through the attachments collection and load each attachment.
foreach (Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
// Load the attachment into a file.
// This call results in a GetAttachment call to EWS.
fileAttachment.Load(StoreFilePath + fileAttachment.Name);
string FileName = fileAttachment.Name;
LogHelper.LogMessage("OutLookMailStart In attachments File Name :" + FileName );
Console.WriteLine("File attachment name: " + fileAttachment.Name);
}
else // Attachment is an item attachment.
{
ItemAttachment itemAttachment = attachment as ItemAttachment;
// Load attachment into memory and write out the subject.
// This does not save the file like it does with a file attachment.
// This call results in a GetAttachment call to EWS.
itemAttachment.Load();
Console.WriteLine("Item attachment name: " + itemAttachment.Name);
}
}
}
catch (Exception ex)
{
LogHelper.LogError("OutLookMailStart -> GetAttachmentsFromEmail Exception");
LogHelper.LogError("Exception Message :" + ex.Message);
if (ex.InnerException != null)
{
LogHelper.LogError("Exception InnerException :" + ex.InnerException);
}
LogHelper.LogError("Exception StackTrace :" + ex.StackTrace);
LogHelper.LogError("OutLookMailStart -> GetAttachmentsFromEmail Exception"); ;
}
LogHelper.LogMessage("<----- GetAttachmentsFromEmail End ----->");
}

How to refund amount of paypal adaptive payment using PayPal.AdaptivePayments SDK?

I`m using PayPal.AdaptivePayments sdk for chained payment and refund process of chained payment.
Using following methods:
for payment : pay() method
for refund : refund() method as per sdk.
When try to refund with payKey then getting response with status: "NO_API_ACCESS_TO_RECEIVER"
Currently I`m sandbox account on development.
I have also followed paypal developer api/sdk docs but still getting same problem.
So please help me to refund process with status of "Refunded".
I have already review post related to this on stack-overflow but I didn`t proper solution in any post.
https://devtools-paypal.com/guide/ap_chained_payment?interactive=ON&env=sandbox
private void Refund(HttpContext contextHttp)
{
NameValueCollection parameters = contextHttp.Request.Params;
RefundRequest request = new RefundRequest(new RequestEnvelope("en_US"));
// Set optional parameters
if(parameters["receiverEmail"].Length > 0)
{
//(Required) Amount to be paid to the receiver
string[] amt = contextHttp.Request.Form.GetValues("receiverAmount");
// Maximum length: 127 characters
string[] receiverEmail = contextHttp.Request.Form.GetValues("receiverEmail");
//Telephone country code
string[] phoneCountry = contextHttp.Request.Form.GetValues("phoneCountry");
string[] phoneNumber = contextHttp.Request.Form.GetValues("phoneNumber");
//Telephone extension
string[] phoneExtn = contextHttp.Request.Form.GetValues("phoneExtn");
string[] primaryReceiver = contextHttp.Request.Form.GetValues("primaryReceiver");
string[] invoiceId = contextHttp.Request.Form.GetValues("invoiceId");
string[] paymentType = contextHttp.Request.Form.GetValues("paymentType");
//(Optional) The transaction subtype for the payment.
string[] paymentSubType = contextHttp.Request.Form.GetValues("paymentSubType");
List<Receiver> receivers = new List<Receiver>();
for(int i=0; i<amt.Length; i++) {
Receiver r = new Receiver(Convert.ToDecimal(amt[i]));
r.email = receiverEmail[i];
r.primary = Convert.ToBoolean(primaryReceiver[i]);
if(invoiceId[i] != string.Empty) {
r.invoiceId = invoiceId[i];
}
if(paymentType[i] != string.Empty) {
r.paymentType = paymentType[i];
}
if(paymentSubType[i] != string.Empty) {
r.paymentSubType = paymentSubType[i];
}
if(phoneCountry[i] != string.Empty && phoneNumber[i] != string.Empty) {
r.phone = new PhoneNumberType(phoneCountry[i], phoneNumber[i]);
if(phoneExtn[i] != string.Empty) {
r.phone.extension = phoneExtn[i];
}
}
receivers.Add(r);
}
request.receiverList = new ReceiverList(receivers);
}
if(parameters["currencyCode"] != string.Empty) {
request.currencyCode = parameters["currencyCode"];
}
if(parameters["payKey"] != string.Empty) {
request.payKey = parameters["payKey"];
}
if(parameters["transactionId"] != string.Empty) {
request.transactionId = parameters["transactionId"];
}
if(parameters["trackingId"] != string.Empty) {
request.trackingId = parameters["trackingId"];
}
AdaptivePaymentsService service = null;
RefundResponse response = null;
try
{
Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();
service = new AdaptivePaymentsService(configurationMap);
response = service.Refund(request);
}
catch (System.Exception e)
{
contextHttp.Response.Write(e.Message);
return;
}
Dictionary<string, string> responseValues = new Dictionary<string, string>();
// string redirectUrl = null;
string redirectUrl = null;
if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
!(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
{
responseValues.Add("Currency code", response.currencyCode);
int idx = 1;
foreach (RefundInfo refund in response.refundInfoList.refundInfo)
{
//Receiver's email address.Maximum length: 127 characters
responseValues.Add("Refund receiver " + idx, refund.receiver.email);
// Amount to be refunded to the receiver.
responseValues.Add("Refund amount " + idx, refund.receiver.amount.ToString());
responseValues.Add("Refund status " + idx, refund.refundStatus);
responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
}
}
Display(contextHttp, "Refund", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
}

Lumisoft.net IMAP server can't add attachments to messages

I'm trying to set up an IMAP server which is pulling data from a SQL database.
I've got the messages working no problems, but I can't work out how to attach attachments to them.
The attachments object on the Mail_Message object also only has a getter and a method called GetAttachments() which doesn't seem to connect to anywhere.
My current code is:
//this is my own object I'm using to pull data from the database
var cmMsg = _ml.GetMessage(mId, session.AuthenticatedUserIdentity.Name, -1);
var msgBody = new MIME_b_Text(MIME_MediaTypes.Text.html);
var msg = new Mail_Message();
msg.Body = msgBody;
msg.To = new Mail_t_AddressList();
msg.From = new Mail_t_MailboxList {new Mail_t_Mailbox(cmMsg.From, cmMsg.FromEmail)};
msg.Cc = new Mail_t_AddressList();
msg.Bcc = new Mail_t_AddressList();
foreach (var recipient in cmMsg.Recipients)
{
if (recipient.isTo)
{
msg.To.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if(recipient.isCC)
{
msg.Cc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if (recipient.isBCC)
{
msg.Bcc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
}
//I tried adding a setter to the attachment object, but just get errors with this code
var a = new List<MIME_Entity>();
foreach (var attachment in cmMsg.Attachments)
{
var aCT = new MIME_b_Multipart(new MIME_h_ContentType("application/octet-stream"));
a.Add(new MIME_Entity
{
Body = aCT,
ContentDisposition = new MIME_h_ContentDisposition("attachment"),
});
}
msg.Attachments = a.ToArray();
msg.Subject = cmMsg.Subject;
msg.Date = cmMsg.TimeDate;
msg.MessageID = cmMsg.InternetMessageId;
if (e.FetchDataType == IMAP_Fetch_DataType.MessageStructure)
{
}
else if(e.FetchDataType == IMAP_Fetch_DataType.MessageHeader)
{
}
else
{
msgBody.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, cmMsg.HtmlBody);
_da.MarkAsRead(archiveID, session.AuthenticatedUserIdentity.Name);
}
e.AddData(info, msg);
I'm not sure if I'm missing something or just got this set up wrong. I noticed there was a MySQL API in the example projects, but that didn't have anything to do with attachments in it either.
Ok so turns out I was going about it the complete wrong way. Below is the code required
Effectively, it requires setting the message to be multipart mixes instead of just text. You can then add the attachments as a body part.
var cmMsg = _ml.GetMessage(mId, session.AuthenticatedUserIdentity.Name, -1);
MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
var msg = new Mail_Message();
msg.To = new Mail_t_AddressList();
msg.From = new Mail_t_MailboxList {new Mail_t_Mailbox(cmMsg.From, cmMsg.FromEmail)};
msg.Cc = new Mail_t_AddressList();
msg.Bcc = new Mail_t_AddressList();
msg.Body = multipartMixed;
foreach (var recipient in cmMsg.Recipients)
{
if (recipient.isTo)
{
msg.To.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if(recipient.isCC)
{
msg.Cc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if (recipient.isBCC)
{
msg.Bcc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
}
msg.Subject = cmMsg.Subject;
msg.Date = cmMsg.TimeDate;
msg.MessageID = cmMsg.InternetMessageId;
msg.MimeVersion = "1.0";
msg.Header.Add(new MIME_h_Unstructured("X-MS-Has-Attach", "yes"));
if (e.FetchDataType == IMAP_Fetch_DataType.MessageStructure)
{
}
else if(e.FetchDataType == IMAP_Fetch_DataType.MessageHeader)
{
}
else
{
MIME_Entity entity_text_plain = new MIME_Entity();
MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
entity_text_plain.Body = text_plain;
text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, cmMsg.HtmlBody);
multipartMixed.BodyParts.Add(entity_text_plain);
foreach (var attachment in cmMsg.Attachments)
{
using (var fs = new FileStream(#"C:\test.txt", FileMode.Open))
{
multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(fs, "test.txt"));
}
}
}
e.AddData(info, msg);

Categories