I want ask if the folder exist, if no create it.I try the foloowing but when I became to the bold row below in the code I get error:NO Command received in Invalid state.
using (ImapClient ic = new ImapClient(imapAddr, myEmailID, myPasswd, ImapClient.AuthMethods.Login, portNo, secureConn))
{
bool headersOnly = false;
ic.SelectMailbox("INBOX");
Lazy<MailMessage>[] messages = ic.SearchMessages(SearchCondition.Unseen(), headersOnly);
foreach (Lazy<MailMessage> message in messages)
{
MailMessage m = message.Value;
AE.Net.Mail.Imap.Mailbox IsExistFolder = ic.Examine("INBOX/zipi4");
if (IsExistFolder == null)
{
ic.CreateMailbox("INBOX/zipi4");
}
string s = "INBOX/zipi2";
**ic.MoveMessage(m.Uid, s);**
ic.Expunge();
TextWriter writer1 = File.CreateText("Y:\\perl4.txt");
m.Save(writer1);
}
}
Related
I have this code that actually works in all cases except when the image is sent by an IOS device, in that case attachments appears in blank.
I connect trough IMAP and take UIDS, then I extract information about email, save attachments and save entire email.
Everything is fine except when the sender attach documents or images by IOS, in that cases the code cant find any documents.
What can I do ?
Thanks
try {
IMailFolder mailFolder = imapClient.GetFolder(Folder);
mailFolder.Open(FolderAccess.ReadOnly);
MimeMessage m = mailFolder.GetMessage(new UniqueId(Decimal.ToUInt32(UID)));
//MailMessage m = imapClient.GetMessage(UID, false, false);
Subject = m.Subject;
From_Name = (m.Sender != null) ? m.Sender.ToString() : "";//m.Sender.DisplayName;
From_Address = (m.From != null) ? m.From.ToString() : "";
Cc_Address = (m.Cc != null) ? m.Cc.ToString() : "";
Date_Sent = m.Date.DateTime;
MessageID = m.MessageId;
Body = m.TextBody;
m.WriteTo (EmailName);
if ( Save_Attachments && Attachments_Path != "") {
System.IO.Directory.CreateDirectory(Attachments_Path);
DataTable dt = new DataTable();
dt.Columns.Add("Path", typeof(String));
foreach (MimeEntity attachment in m.Attachments)
{
if (attachment is MimePart)
{
MimePart part = (MimePart)attachment;
string path = System.IO.Path.Combine(Attachments_Path, removeIllegal(part.FileName));
using (var stream = File.Create(path))
{
part.Content.DecodeTo(stream);
}
DataRow dr = dt.NewRow();
dr["Path"] = path;
dt.Rows.Add(dr);
}
}
Attachments = dt;
} else {
Attachments = null;
}
}
catch (Exception ex) {
Subject = "";
From_Name = "";
From_Address = "";
Cc_Address = "";
Date_Sent = new DateTime();
MessageID = "";
Body = "";
Attachments = null;
throw ex;
}
Instead of using MimeMessage.Attachments, you need to use MimeMessage.BodyParts - but be aware that BodyParts also contains the text body of the message.
I have more information here: http://www.mimekit.net/docs/html/Working-With-Messages.htm
A quick & dirty way of accomplishing what you want to do is probably something like this:
foreach (var attachment in m.BodyParts.Where (x => x.ContentDisposition?.FileName != null))
(Note: you'll need to make sure to add using System.Linq; at the top of your C# file)
I'm trying to make an program that send a file to a mobile device encrypted, and the device will get it in another program and decrypt it.
So far I've done the bluetooth connection:
private void Connect()
{
using (SelectBluetoothDeviceDialog bldialog = new SelectBluetoothDeviceDialog())
{
bldialog.ShowAuthenticated = true;
bldialog.ShowRemembered = true;
bldialog.ShowUnknown = true;
if (bldialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
if (bldialog.SelectedDevice == null)
{
System.Windows.Forms.MessageBox.Show("No device selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
BluetoothDeviceInfo selecteddevice = bldialog.SelectedDevice;
BluetoothEndPoint remoteEndPoint = new BluetoothEndPoint(selecteddevice.DeviceAddress, BluetoothService.ObexFileTransfer);
client = new BluetoothClient();
client.Connect(remoteEndPoint);
session = new ObexClientSession(client.GetStream(), UInt16.MaxValue);
session.Connect(ObexConstant.Target.FolderBrowsing);
tbConnectionDet.Text = string.Format("Connected to: {0}", selecteddevice.DeviceName);
}
}
}
Also I'm sending the file this way:
private void UploadFiles(string[] files)
{
long size = 0;
List<string> filestoupload = new List<string>();
foreach (string filename in files)
{
if (File.Exists(filename))
{
FileInfo info = new FileInfo(filename);
filestoupload.Add(filename);
size += info.Length;
}
}
using (FileForm upform = new FileForm(new List<string>(filestoupload),
false, session, size, null))
{
upform.ExceptionMethod = ExceptionHandler;
upform.ShowDialog();
lsvExplorer.BeginUpdate();
for (int i = 0; i <= upform.FilesUploaded; i++)
{
ListViewItem temp = new ListViewItem(new string[]{ Path.GetFileName(filestoupload[i]),
FormatSize(new FileInfo(filestoupload[i]).Length, false)},
GetIconIndex(Path.GetExtension(filestoupload[i]), false));
temp.Tag = false;
lsvExplorer.Items.Add(temp);
}
lsvExplorer.EndUpdate();
}
}
I'm using 32feet and BrechamObex libraries .
I have the following questions :
I want to send a public key from my phone to my computer then encrypt a file and send it back to my phone. After I receive the file, I want to decrypt it so I will need another program in order to do this. How can I send information from one program to another using bluetooth?
Whenever I send a file, the phone gets it, but the size it always 0
I am using ASP.Net MVC.
using (ExchangeServiceBinding exchangeServer = new ExchangeServiceBinding())
{
ICredentials creds = new NetworkCredential("username", "password");
exchangeServer.Credentials = creds;
exchangeServer.Url = "https://myexchangeserver.com/EWS/Exchange.asmx";
FindItemType findItemRequest = new FindItemType();
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
// define which item properties are returned in the response
ItemResponseShapeType itemProperties = new ItemResponseShapeType();
itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
findItemRequest.ItemShape = itemProperties;
// identify which folder to search
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.inbox;
// add folders to request
findItemRequest.ParentFolderIds = folderIDArray;
// find the messages
FindItemResponseType findItemResponse = exchangeServer.FindItem(findItemRequest);
// read returned
FindItemResponseMessageType folder = (FindItemResponseMessageType)findItemResponse.ResponseMessages.Items[0];
ArrayOfRealItemsType folderContents = new ArrayOfRealItemsType();
folderContents = (ArrayOfRealItemsType)folder.RootFolder.Item;
ItemType[] items = folderContents.Items;
// if no messages were found, then return null -- we're done
if (items == null || items.Count() <= 0)
{ return null; }
// FindItem never gets "all" the properties, so now that we've found them all, we need to get them all.
BaseItemIdType[] itemIds = new BaseItemIdType[items.Count()];
for (int i = 0; i < items.Count(); i++)
{
itemIds[i] = items[i].ItemId;
}
GetItemType getItemType = new GetItemType();
getItemType.ItemIds = itemIds;
getItemType.ItemShape = new ItemResponseShapeType();
getItemType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
getItemType.ItemShape.BodyType = BodyTypeResponseType.HTML;
getItemType.ItemShape.BodyTypeSpecified = true;
GetItemResponseType getItemResponse = exchangeServer.GetItem(getItemType);
ItemType[] messages = new ItemType[getItemResponse.ResponseMessages.Items.Count()];
List<MailRecipientModel> model = new List<MailRecipientModel>();
for (int j = 0; j < messages.Count(); j++)
{
messages[j] = ((ItemInfoResponseMessageType)getItemResponse.ResponseMessages.Items[j]).Items.Items[0];
MailRecipientModel model1 = new MailRecipientModel();
model1.Subject = messages[j].Subject;
model1.FromAddress = messages[j].Sender.Item.EmailAddress;
model1.DisplayName = messages[j].Sender.Item.Name;
model1.Date = messages[j].DateTimeReceived.Date.ToString();
model1.MailBody = messages[j].Body.Value;
model1.MsgId = messages[j].ItemId.Id;
if (messages[j].Attachments != null) {
//
}
model.Add(model1);
}
return model;
}
This my code I wanna download attachment file and if attachment file is image so its display in browser.
I am using Microsoft ActiveSync Exchange Server.
If you know how to do so please help me.
public List<FileAttachment> getAttachmentFromExchangeAccount( ExchangeAccounts exchangeAccount, String attachmentId, String itemId) {
ExchangeService service = obtainExchangeService(exchangeAccount);
List<FileAttachment> fileAttachmentsEWS = new ArrayList<>();
try {
EmailMessage message = EmailMessage.bind(service, new ItemId(attachmentId), new PropertySet(ItemSchema.Attachments));
message.load();
for (Attachment attachment : message.getAttachments()) {
attachment.load();
if (attachment.getId().equals(itemId)) {
FileAttachment fileAttachment = (FileAttachment) attachment;
fileAttachment.load();
fileAttachmentsEWS.add(fileAttachment);
}
}
} catch (ServiceLocalException e) {
LOG.debug("OUT NOK loadAttachmentFile ServiceLocalException");
LOG.debug(e.getMessage());
} catch (Exception e) {
LOG.debug("OUT NOK loadAttachmentFile Exception");
LOG.debug(e.getMessage());
}
return fileAttachmentsEWS;
}
You should be using the GetAttachment operation https://msdn.microsoft.com/en-us/library/office/aa494316(v=exchg.150).aspx . There is a Proxy code sample https://blogs.msdn.microsoft.com/vikas/2007/10/15/howto-ews-use-getattachment-to-download-attachments-off-mailappointment/
I have created a Web Email Application, How do I view and save attached files?
I am using OpenPop, a third Party dll, I can send emails with attachments and read emails with no attachments.
This works fine:
Pop3Client pop3Client = (Pop3Client)Session["Pop3Client"]; // Creating newPopClient
int messageNumber = int.Parse(Request.QueryString["MessageNumber"]);
Message message = pop3Client.GetMessage(messageNumber);
MessagePart messagePart = message.MessagePart.MessageParts[1];
lblFrom.Text = message.Headers.From.Address; // Writeing message.
lblSubject.Text = message.Headers.Subject;
lblBody.Text=messagePart.BodyEncoding.GetString(messagePart.Body);
This second portion of code displays the contents of the attachment, but that's only useful if its a text file. I need to be able to save the attachment. Also the bottom section of code I have here over writes the body of my message, so if I receive an attachment I can't view my message body.
if (messagePart.IsAttachment == true) {
foreach (MessagePart attachment in message.FindAllAttachments()) {
if (attachment.FileName.Equals("blabla.pdf")) { // Save the raw bytes to a file
File.WriteAllBytes(attachment.FileName, attachment.Body); //overwrites MessagePart.Body with attachment
}
}
}
If anyone is still looking for answer this worked fine for me.
var client = new Pop3Client();
try
{
client.Connect("MailServerName", Port_Number, UseSSL); //UseSSL true or false
client.Authenticate("UserID", "password");
var messageCount = client.GetMessageCount();
var Messages = new List<Message>(messageCount);
for (int i = 0;i < messageCount; i++)
{
Message getMessage = client.GetMessage(i + 1);
Messages.Add(getMessage);
}
foreach (Message msg in Messages)
{
foreach (var attachment in msg.FindAllAttachments())
{
string filePath = Path.Combine(#"C:\Attachment", attachment.FileName);
if(attachment.FileName.Equals("blabla.pdf"))
{
FileStream Stream = new FileStream(filePath, FileMode.Create);
BinaryWriter BinaryStream = new BinaryWriter(Stream);
BinaryStream.Write(attachment.Body);
BinaryStream.Close();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("", ex.Message);
}
finally
{
if (client.Connected)
client.Dispose();
}
for future readers there is easier way with newer releases of Pop3
using( OpenPop.Pop3.Pop3Client client = new Pop3Client())
{
client.Connect("in.mail.Your.Mailserver.com", 110, false);
client.Authenticate("usernamePop3", "passwordPop3", AuthenticationMethod.UsernameAndPassword);
if (client.Connected)
{
int messageCount = client.GetMessageCount();
List<Message> allMessages = new List<Message>(messageCount);
for (int i = messageCount; i > 0; i--)
{
allMessages.Add(client.GetMessage(i));
}
foreach (Message msg in allMessages)
{
var att = msg.FindAllAttachments();
foreach (var ado in att)
{
ado.Save(new System.IO.FileInfo(System.IO.Path.Combine("c:\\xlsx", ado.FileName)));
}
}
}
}
The OpenPop.Mime.Message class has ToMailMessage() method that converts OpenPop's Message to System.Net.Mail.MailMessage, which has an Attachments property. Try extracting attachments from there.
I wrote this quite a long time ago, but have a look at this block of code that I used for saving XML attachments within email messages sat on a POP server:
OpenPOP.POP3.POPClient client = new POPClient("pop.yourserver.co.uk", 110, "your#email.co.uk", "password_goes_here", AuthenticationMethod.USERPASS);
if (client.Connected) {
int msgCount = client.GetMessageCount();
/* Cycle through messages */
for (int x = 0; x < msgCount; x++)
{
OpenPOP.MIMEParser.Message msg = client.GetMessage(x, false);
if (msg != null) {
for (int y = 0; y < msg.AttachmentCount; y++)
{
Attachment attachment = (Attachment)msg.Attachments[y];
if (string.Compare(attachment.ContentType, "text/xml") == 0)
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
string xml = attachment.DecodeAsText();
doc.LoadXml(xml);
doc.Save(#"C:\POP3Temp\test.xml");
}
}
}
}
}
List<Message> lstMessages = FetchAllMessages("pop.mail-server.com", 995, true,"Your Email ID", "Your Password");
The above line of code gets the list of all the messages from your email using corresponding pop mail-server.
For example, to get the attachment of latest (or first) email in the list, you can write following piece of code.
List<MessagePart> lstAttachments = lstMessages[0].FindAllAttachments(); //Gets all the attachments associated with latest (or first) email from the list.
for (int attachment = 0; attachment < lstAttachments.Count; attachment++)
{
FileInfo file = new FileInfo("Some File Name");
lstAttachments[attachment].Save(file);
}
private KeyValuePair<byte[], FileInfo> parse(MessagePart part)
{
var _steam = new MemoryStream();
part.Save(_steam);
//...
var _info = new FileInfo(part.FileName);
return new KeyValuePair<byte[], FileInfo>(_steam.ToArray(), _info);
}
//... How to use
var _attachments = message
.FindAllAttachments()
.Select(a => parse(a))
;
Just in case someone wants the code for VB.NET:
For Each emailAttachment In client.GetMessage(count).FindAllAttachments
AttachmentName = emailAttachment.FileName
'----// Write the file to the folder in the following format: <UniqueID> followed by two underscores followed by the <AttachmentName>
Dim strmFile As New FileStream(Path.Combine("C:\Test\Attachments", EmailUniqueID & "__" & AttachmentName), FileMode.Create)
Dim BinaryStream = New BinaryWriter(strmFile)
BinaryStream.Write(emailAttachment.Body)
BinaryStream.Close()
Next
I need to extract/export the lotus notes email attachment into file system. for that I wrote following method but each time I am receiving an error at line foreach (NotesItem nItem in items).. Can anybody please tell me what I am doing wrong ..
Thanks
Jwalin
public void GetAttachments()
{
NotesSession session = new NotesSession();
//NotesDocument notesDoc = new NotesDocument();
session.Initialize("");
NotesDatabase NotesDb = session.GetDatabase("", "C:\\temps\\lotus\\sss11.nsf", false); //Open Notes Database
NotesView inbox = NotesDb.GetView("By _Author");
NotesDocument docInbox = inbox.GetFirstDocument();
object[] items = (object[])docInbox.Items;
**foreach (NotesItem nItem in items)**
{
//NotesItem nItem = (NotesItem)o1;
if (nItem.Name == "$FILE")
{
NotesItem file = docInbox.GetFirstItem("$File");
string fileName = ((object[])nItem.Values)[0].ToString();
NotesEmbeddedObject attachfile = (NotesEmbeddedObject)docInbox.GetAttachment(fileName);
if (attachfile != null)
{
attachfile.ExtractFile("C:\\temps\\export\\" + fileName);
}
}
}
You don't need to use the $File item to get the attachment name(s). Rather, you can use the HasEmbedded and EmbeddedObject properties of the NotesDocument class.
public void GetAttachments()
{
NotesSession session = new NotesSession();
//NotesDocument notesDoc = new NotesDocument();
session.Initialize("");
NotesDatabase NotesDb = session.GetDatabase("", "C:\\temps\\lotus\\sss11.nsf", false); //Open Notes Database
NotesView inbox = NotesDb.GetView("By _Author");
NotesDocument docInbox = inbox.GetFirstDocument();
// Check if any attachments
if (docInbox.hasEmbedded)
{
NotesEmbeddedObject attachfile = (NotesEmbeddedObject)docInbox.embeddedObjects[0];
if (attachfile != null)
{
attachfile.ExtractFile("C:\\temps\\export\\" + attachfile.name);
}
}
Ed's solution didn't work for me. Something about my Notes db design seems to have left the EmbeddedObjects property null even when the HasEmbedded flag is true. So I sort of combined the Ed's and Jwalin's solutions, modifying them to fetch all attachments from a Notes document.
NotesDocument doc = viewItems.GetNthEntry(rowCount).Document;
if (doc.HasEmbedded)
{
object[] items = (object[])doc.Items;
foreach (NotesItem item in items)
{
if(item.Name.Equals("$FILE"))
{
object[] values = (object[])item.Values;
doc.GetAttachment(values[0].ToString()).ExtractFile(fileSavePath + values[0].ToString());
}
}