I am trying to delete message from inbox. Message doesn't have messageId(it's not gmail)
I've found in this topic the solution
MailSystem.Net Delete Message, IndexOnServer Property = 0
However it doesn't work for me.
The code below is simplifed the application works as MVVM light application.
This is how I get emails.
for (int i = 1; i <= mails.MessageCount; ++i)
{
Message msg = fetch.MessageObject(i);
MessageModel tmpMsg = new MessageModel() { messageType = MessageModel.MessageType.INBOX, UID = i, Date = msg.Date, Body = content, Title = msg.Subject, Sender = msg.From.Merged, Receiver = msg.To[0].Merged, IsEncrypted = isEncrypted };
tmpMsg.MessageWasDeleted += tmpMsg_MessageWasDeleted;
InboxMessages.Messages.Add(tmpMsg); //this is observable collection of MessageModel
}
I've tested this code and proper id is added to messageModel object.
Now when I want to delete the message I use this code in model:
var imapClient = new Imap4Client();
imapClient.BeginConnect(ConfigurationManager.AppSettings["mail_smtp_host"], ConfigurationManager.AppSettings["mail_smtp_login"], ConfigurationManager.AppSettings["mail_smtp_password"], new AsyncCallback((res) =>
{
imapClient.EndConnect(res);
//var box = imapClient.AllMailboxes["INBOX"] ;
var box = imapClient.SelectMailbox("INBOX");
Message email = box.Fetch.MessageObject(UID); //this is just to check if proper message is going to be deleted
box.UidDeleteMessage(UID, true);
if (MessageWasDeleted != null) MessageWasDeleted(this, new EventArgs());
}));
This method removes the message based on UID(at least it should do it) but it doesn't. There is no error nothing appears.
Where I could make an error? What's the proper way to delete message using ActiveUpMail?
Related
I am having the hardest time figuring out how to create a pdf and attach it to an automated email. I thought it wouldn't be that hard but have quickly found out that it is much more complex than I imagined. Anyways, what I am doing is I have an order form, and when the customer fills out an order and submits it, I want it to generate a PDF for that order and attach it to an automated confirmation email. I am currently using Rotativa to generate the pdf and if I just ran the action result for generating it, it works perfectly fine which looks something like this:
public ActionResult ProcessOrder(int? id)
{
string orderNum = "FulfillmentOrder" + orderDetail.OrderID + ".pdf";
var pdf = new ActionAsPdf("OrderReportPDF", new { id = orderDetail.OrderID }) { FileName = orderNum };
return pdf;
}
When I added the function to send an automated email after the order form was submitted, that works perfectly fine with just the email by itself. But I can't seem to figure out how to generate the pdf and attach it to the email. The report view that gets the data from the order form is called "OrderReportPDF". My order form is called "Checkout", but the action result I use for this is called "Process Order". I've taken out the code in this function that is for the order form as it is not applicable. The section of my code for sending the email after the form is submitted is:
public ActionResult ProcessOrder(int? id)
{
//Send a confirmation email
var msgTitle = "Order Confirmation #" + orderDetail.OrderID;
var recipient = JohnDoe;
var fileAttach = //This is where I can't figure out how to attach//
var fileList = new string[] { fileAttach };
var errorMessage = "";
var OrderConfirmation = "Your order has been placed and is pending review." +
" Attached is a copy of your order.";
try
{
// Initialize WebMail helper
WebMail.SmtpServer = "abc.net";
WebMail.SmtpPort = 555;
WebMail.UserName = recipient;
WebMail.Password = "12345";
WebMail.From = "orders#samplecode.com";
// Send email
WebMail.Send(to: "orders#samplecode.com",
subject: msgTitle,
body: OrderConfirmation,
filesToAttach: fileList
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
//5. Remove item cart session
Session.Remove(strCart);
return View("OrderSuccess");
}
I have been able to find very few articles on this issue using Rotativa and the ones I have found don't work for what I'm doing. Maybe Rotativa won't work for this, I'm hoping it does because I've designed my pdf report it generates from it, and not sure if doing it another way will screw up my formatting of it or not. As you can see at the bottom of the code, I return the view to an "OrderSuccess" page. When I try to implement the first code into the second code, it won't let me "return pdf" to execute the ActionAsPdf that generates the pdf when I do the "return View("OrderSuccess")". It only lets me do one or the other. If anybody knows how I can accomplish this, I need some help. I appreciate any suggestions or feedback. I'm pretty new to this so please be patient with me if I don't understand something.
Here is the updated code that fixed my problem and created the pdf, then attached it to an automated email once the order form was submitted:
public ActionResult ProcessOrder(int? id)
{
//1. Generate pdf file of order placed
string orderNum = "FulfillmentOrder" + orderDetail.OrderID + ".pdf";
var actionResult = new Rotativa.ActionAsPdf("OrderReportPDF", new { id = orderDetail.OrderID }) { FileName = orderNum };
var PdfAsBytes = actionResult.BuildFile(this.ControllerContext);
//2. Send confirmation email
var msgTitle = "Order Confirmation #" + orderDetail.OrderID;
var OrderConfirmation = "Your order has been placed and is pending review.<br />" +
" Attached is a copy of your order." +
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("orders#samplecode.com");
mail.To.Add("orders#samplecode.com");
mail.Subject = msgTitle;
mail.Body = OrderConfirmation;
mail.IsBodyHtml = true;
//STREAM THE CONVERTED BYTES AS ATTACHMENT HERE
mail.Attachments.Add(new Attachment(new MemoryStream(PdfAsBytes), orderNum));
using (SmtpClient smtp = new SmtpClient("abc.net", 555))
{
smtp.Credentials = new NetworkCredential("orders#samplecode.com", "password!");
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
//3. Remove item cart session
Session.Remove(strCart);
return View("OrderSuccess");
}
Thank you again to the people that helped and got me pointed in the right direction! Also, a quick shout out to #Drewskis who posted this answer in convert Rotativa.ViewAsPdf to System.Mail.Attachment where I was able to use it to solve my issue!
I am using DNN 9 and I want to send a notification with an attachment file, but seems that DNN doesn't allow to do that.
Is there is a way (or any workaround) to do that?
Here is the DNN code of the NotificationsController
and here is my code that calls the DNN code
//...
Notification dnnNotification = new Notification
{
NotificationTypeID = notification.NotificationTypeId,
From = notification.From,
Subject = notification.Subject,
Body = notification.Body
};
NotificationsController.Instance.SendNotification(dnnNotification, portalId, dnnRoles, dnnUsers);
You cannot attach a file to a notification in DNN. BUT, you can add custom notification actions to a notification type. These actions result in links added under the notification (like the default "Dismiss" action to mark the notification as "read").
In order to send a notification, you need to create a NotificationType to associate that to. The NotificationTypeAction are added to the type. So whenever you send a notification of a certain type, the actions go with it.
You could create a NotificationTypeAction and name it "Download Attachment". When a user clicks the link, it will call a custom api service. That service could serve up the file.
Here is some sample code in which I create a custom type with 1 custom action:
public void AddNotificationType()
{
var actions = new List<NotificationTypeAction>();
var deskModuleId = DesktopModuleController.GetDesktopModuleByFriendlyName(Constants.DESKTOPMODULE_FRIENDLYNAME).DesktopModuleID;
var objNotificationType = new NotificationType
{
Name = Constants.NOTIFICATION_FILEDOWNLOAD,
Description = "Get File Attachment",
DesktopModuleId = deskModuleId
};
if (NotificationsController.Instance.GetNotificationType(objNotificationType.Name) == null)
{
var objAction = new NotificationTypeAction
{
NameResourceKey = "DownloadAttachment",
DescriptionResourceKey = "DownloadAttachment_Desc",
APICall = "DesktopModules/MyCustomModule/API/mynotification/downloadfile",
Order = 1
};
actions.Add(objAction);
NotificationsController.Instance.CreateNotificationType(objNotificationType);
NotificationsController.Instance.SetNotificationTypeActions(actions, objNotificationType.NotificationTypeId);
}
}
Then use code like the following to send the notification:
public void SendNotification(UserInfo userToReceive)
{
// Get the notification type; if it doesn't exist, create it
ModuleController mCtrl = new ModuleController();
var itemAddedNType = NotificationsController.Instance.GetNotificationType(Constants.NOTIFICATION_FILEDOWNLOAD);
if (itemAddedNType == null)
{
AddNotificationType();
itemAddedNType = NotificationsController.Instance.GetNotificationType(Constants.NOTIFICATION_FILEDOWNLOAD);
}
if (itemAddedNType != null)
{
Notification msg = new Notification
{
NotificationTypeID = itemAddedNType.NotificationTypeId,
Subject = "A file is ready to download.",
Body = alertBody,
ExpirationDate = DateTime.MaxValue,
IncludeDismissAction = true,
};
List<UserInfo> sendUsers = new List<UserInfo>();
sendUsers.Add(userToReceive);
NotificationsController.Instance.SendNotification(msg, itemModule.PortalID, null, sendUsers);
}
}
For a full tutorial on DNN Notifications, I highly recommend subscribing to DNNHero.com and watching this 3-part series which comes with sample code.
https://www.dnnhero.com/Premium/Tutorial/ArticleID/265/DNN-Notifications-Introduction-Part-1-3
i'm trying to send message to People user name for example my friends username is #...
but no thing happend
no Error
and no send
can i use this library ?
or just with tlsharp?
how can i found apiid and hashid for my bot?
using Telegram.Bot;
and
public partial class Form1 : Form
{
Telegram.Bot. TelegramBotClient bot = new TelegramBotClient("token");
Thread a;
public Form1()
{
InitializeComponent();
}
public void GetUpdates()
{
int offset = 0;
while (true)
{
Telegram.Bot.Types.Update[] updates =
bot.GetUpdatesAsync(offset).Result;
foreach (var update in updates)
{
offset = update.Id + 1;
if (update.Message == null)
continue;
var from = update.Message.From.FirstName;
var text = update.Message.Text;
string chatid = update.Message.Chat.Id;
string username = update.Message.From.Username;
// label1.BeginInvoke(delegate { label1.Text = label1.BeginInvoke(delegate { label1.Text = string.Format("sender:{0}\ntext:{1}\ncatid:{2}", from, text, chatid); }); });
// lblshow.Text = string.Format("sender:{0}\ntext:{1}\ncatid:{2}", from, text, chatid);
//label1.Text = string.Format("sender:{0}\ntext:{1}\ncatid:{2}", from, text, chatid);
this.BeginInvoke((System.Windows.Forms.MethodInvoker)delegate () {textBox1.Text = string.Format("sender:{0}\ntext:{1}\ncusername:{2}", from, text, username); });
bot.SendTextMessageAsync( chatid, "سلام بر شما");
//is this correct for send to people?
bot.SendTextMessageAsync("#Hoda.....", "hi");
}
}
you cant send message to user by user Name.telegram bot API only accept user Id. (except channels).
When you try to send messages to users you must know their chatID (chatID is a long number which is unique for every user in telegram and never changes while username can be changed) or you must have stored their chatIDs in a database or a file or ...
This means a user must have sent at least one message to your bot before this includes the /start command. Then your bot can find out their chatID and using that chatID, you can send whatever you want to that user unless he/she has blocked your bot by pressing Delete and Stop button when trying to delete the conversation between him/her and your bot.
You can but don't pass # symbol, If the username is #me pass "me" to SendTextMessageAsync without passing #.
I am using the Exchange Web Services Managed API 2.2 to monitor users inboxes and need to determine if an e-mail is a new item, a reply or a forwarded message.
I have seen various articles on SO such as how to notice if a mail is a forwarded mail? and Is there a way to determine if a email is a reply/response using ews c#? which both help in their specific cases but I still cannot work out how to distinguish between a reply and a forwarded item.
In the first article an extra 5 bytes is added each time (forward or reply) so I don't know what the last action was.
The second article suggests using the InReplyTo however when I examine the property for forwarded e-mails it contains the original senders e-mail address (not null).
I have seen other articles such as this or this that suggest using extended properties to examine the values in PR_ICON_INDEX, PR_LAST_VERB_EXECUTED and PR_LAST_VERB_EXECUTION_TIME.
My code looks as follows but never returns a value for lastVerbExecuted
var lastVerbExecutedProperty = new ExtendedPropertyDefinition(4225, MapiPropertyType.Integer);
var response = service.BindToItems(newMails, new PropertySet(BasePropertySet.IdOnly, lastVerbExecutedProperty));
var items = response.Select(itemResponse => itemResponse.Item);
foreach (var item in items)
{
object lastVerb;
if (item.TryGetProperty(lastVerbExecutedProperty, out lastVerb))
{
// do something
}
}
PR_ICON_INDEX, PR_LAST_VERB_EXECUTED and PR_LAST_VERB_EXECUTION_TIME would only work to tell you if the recipient has acted on a message in their Inbox. Eg if the user had replied or forwarded a message in their inbox then these properties get set on the message in their Inbox. On the message that was responded to or forwarded these properties would not be set. I would suggest you use the In-Reply-To Transport header which should be set on any message that is replied to or forwarded, this should contain the internet messageid of the message that was replied to or forwarded eg.
FindItemsResults<Item> fiRs = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
PropertySet fiRsPropSet = new PropertySet(BasePropertySet.FirstClassProperties);
ExtendedPropertyDefinition PR_TRANSPORT_MESSAGE_HEADERS = new ExtendedPropertyDefinition(0x007D, MapiPropertyType.String);
fiRsPropSet.Add(PR_TRANSPORT_MESSAGE_HEADERS);
service.LoadPropertiesForItems(fiRs.Items, fiRsPropSet);
foreach (Item itItem in fiRs)
{
Object TransportHeaderValue = null;
if(itItem.TryGetProperty(PR_TRANSPORT_MESSAGE_HEADERS,out TransportHeaderValue)) {
string[] stringSeparators = new string[] { "\r\n" };
String[] taArray = TransportHeaderValue.ToString().Split(stringSeparators, StringSplitOptions.None);
for (Int32 txCount = 0; txCount < taArray.Length; txCount++)
{
if (taArray[txCount].Length > 12)
{
if (taArray[txCount].Substring(0, 12).ToLower() == "in-reply-to:")
{
String OriginalId = taArray[txCount].Substring(13);
Console.WriteLine(OriginalId);
}
}
}
}
}
Apart from the Subject prefix that was discussed in the other link I don't know of any other proprieties that will differentiate between a reply or forward.
Cheers
Glen
The best way to rely is on the ResponeCode of Extended properties
Refer below scripts
private static int IsForwardOrReplyMail(ExchangeService service, EmailMessage messageToCheck)
{
try
{
// Create extended property definitions for PidTagLastVerbExecuted and PidTagLastVerbExecutionTime.
ExtendedPropertyDefinition PidTagLastVerbExecuted = new ExtendedPropertyDefinition(0x1081, MapiPropertyType.Integer);
ExtendedPropertyDefinition PidTagLastVerbExecutionTime = new ExtendedPropertyDefinition(0x1082, MapiPropertyType.SystemTime);
PropertySet propSet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Subject, PidTagLastVerbExecutionTime, PidTagLastVerbExecuted);
messageToCheck = EmailMessage.Bind(service, messageToCheck.Id, propSet);
// Determine the last verb executed on the message and display output.
object responseType;
messageToCheck.TryGetProperty(PidTagLastVerbExecuted, out responseType);
if (responseType != null && ((Int32)responseType) == 104)
{
//FORWARD
return 104;
}
else if (responseType != null && ((Int32)responseType) == 102)
{
//REPLY
return 102;
}
}
catch (Exception)
{
return 0;
//throw new NotImplementedException();
}
}
To determine if it was a reply to a email, you can use the EmailMessage objects InReplyTo property, e.g:
EmailMessage mail = ((EmailMessage)Item.Bind(service, new ItemId(UniqueId)));
if (mail.InReplyTo == null)
return;
else
..your code
In Outlook, I can set the subject for a new message (when composing a new mail message), but I want to prepend text. So I need to get the subject first, and then set it.
Outlook.Application application = Globals.ThisAddIn.Application;
Outlook.Inspector inspector = application.ActiveInspector();
Outlook.MailItem myMailItem = (Outlook.MailItem)inspector.CurrentItem;
if (myMailItem != null && !string.IsNullOrEmpty(myMailItem.Subject))
{
myMailItem.Subject = "Following up on your order";
}
This code works on replies, but not for new messages, because in that case, myMailItem is null.
This is what I was looking for:
if (thisMailItem != null)
{
thisMailItem.Save();
if (thisMailItem.EntryID != null)
{
thisMailItem.Subject = "prepended text: " + thisMailItem.Subject;
thisMailItem.Send();
}
}
The subject was null until the mail item had been saved, either because it was sent, or as a draft. We can save it programmatically and then get the subject.
One other note: if the subject is blank at the time of saving, it will still show as null.