I am using Pop3Client for reading email. The email I'm reading has some files attached. The attached files contain HTML content, so I want to read the file contents as HTML
My code
var Messages = new List<Message>(messageCount); // messageCount = total unread email
for (int i = 0; i < messageCount; i++)
{
Message getMessage = client.GetMessage(i + 1);
Messages.Add(getMessage);
}
int k = 1;
foreach (Message msg in Messages)
{
foreach (var attachment in msg.FindAllAttachments())
{
var html = attachment.GetBodyAsText();
}
}
Output
But I need the output in HTML format; how can I convert the output to HTML?
Related
I've the following data format in a NotePad file:
123456:
7891011:
So with the following code, I can replace colon from every line and get the below result:
var line = File.ReadAllLines("D:\\Sample.txt");
for (int i = 0; i < line.Length; i++)
{
var fields = line[i].Remove(30);
MessageBox.Show(fields.ToString());
TextWriter txt = new StreamWriter("D:\\Demo.txt");
txt.Write(line[i]);
txt.Close();
}
Output:
123456
7891011
But when I try to save the formatted data in a new NotePad file, it only saves one data. Is there anything I am doing wrong?
You always create a new StreamWriter within the line loop and overwrite the existing data. Try:
var line = File.ReadAllLines("D:\\Sample.txt");
using (TextWriter txt = new StreamWriter("D:\\Demo.txt"))
{
for (int i = 0; i < line.Length; i++)
{
var fields = line[i].Remove(30);
//MessageBox.Show(fields.ToString());
txt.Write(line[i]);
}
txt.Close();
}
I'm trying to copy my inbox email to text file then search word in this text file. if this word exist i will use this word to query email-id from db finally forward this mail to this email-id.
my problem is i m not able to copy email into text file. msg variable always empty
this my code :
using (Pop3Client client = new Pop3Client())
{
client.Connect("pop.gmail.com", 995, true);
client.Authenticate("mymail#gmail.com", "pasword", AuthenticationMethod.UsernameAndPassword);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
for (int i = messageCount; i > 0; i--)
{
string msg = client.GetMessage(i).MessagePart.GetBodyAsText().ToString();
System.IO.File.WriteAllText(#"d:\\My File2.log", msg.ToString());
var body = System.IO.File.ReadLines(#"d:\\My File2.log");
if (body.Contains("cusotmer ID: X"))
{
getemailadress();
sendemail();
}
}
}
could you use this code :
var mailbody = ASCIIEncoding.ASCII.GetString(message.RawMessage);
like this :
using (Pop3Client client = new Pop3Client())
{
client.Connect("pop.gmail.com", 995, true);
client.Authenticate("mymail#gmail.com", "pasword", AuthenticationMethod.UsernameAndPassword);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
for (int i = messageCount; i > 0; i--)
{
string msg = ASCIIEncoding.ASCII.GetString(client.GetMessage(i).RawMessage);
System.IO.File.WriteAllText(#"d:\\My File2.log", msg);
var body = System.IO.File.ReadLines(#"d:\\My File2.log");
if (body.Contains("cusotmer ID: X"))
{
getemailadress();
sendemail();
}
}
}
And, advice: stop call .ToString() for already string objects.
And i cannot understand why you trying to save messageBody to a TextFile. Because WriteAllText function will overwrite this file on each loop.
So you wont find your all message end of this method. You can find only last message body in the textfile. Are you noticed this?
I am writing a program in C# to access the UNREAD emails from Gmail using ImapX (Version 2.0.0.13). I wish to download specifically the powerpoint (.ppt or .pptx) files in the attachment. I have made the download of attachment work.
However, the downloads are not saved correctly on the disk. For example, if an attachment is of size 3.5 MB only 2.4 MB of it is saved.
Am I missing a step here?
Here is my code:
using(ImapClient client = new ImapClient(host, port, true, true))
{
if (client.Login(username, password))
{
FolderCollection folders = client.Folders;
Message[] messages = client.Folders["INBOX"].Search("UNSEEN", MessageFetchMode.Attachments, 100);
for (int i = 0; i < messages.Length; i++)
{
if (messages[i].Attachments.Length > 0)
{
Attachment[] atts = messages[i].Attachments;
for (int j = 0; j < atts.Length; j++)
{
if (atts[j].FileName.Contains("ppt") || atts[j].FileName.Contains("pptx"))
{
atts[j].Download();
atts[j].Save(SAVE_LOCATION, atts[j].FileName);
}
}
}
}
}
}
The problem was solved after I downloaded the updated source code from the ImapX site. It works perfectly now with the above source code.
I have a page where the User can either upload their own csv or enter values into a listbox which then creates a csv (in the background). Regardless of which way the csv gets created I need to upload that csv to our server via a byte stream.
My problem is that when Im creating the csv I shouldn't have to create a temporary file, I should be able to write to the stream then read it back for uploading. How can I remove the need for the temporary file?
current code which works (but uses temp file):
try {
string filename = DateTime.Now.ToString("MMddyyHmssf");
filename = filename + ".csv";
string directory = ConfigurationManager.AppSettings["TempDirectory"].ToString();
path = Path.Combine(directory, filename);
using (StreamWriter sw = File.CreateText(path)) {
foreach (ListItem item in this.lstAddEmailAddress.Items) {
sw.WriteLine(" , ," + item.ToString());
}
}
} catch (Exception ex) {
string error = "Cannot create temp csv file used for importing users by email address. Filepath: " + path + ". FileException: " + ex.ToString();
this.writeToLogs(error, 1338);
}
}
// put here for testing the byte array being sent vs ready byte[] byteArray = System.IO.File.ReadAllBytes(path);
myCsvFileStream = File.OpenRead(path);
nFileLen = (int)myCsvFileStream.Length;
I have tried
Stream myCsvFileStream;
using (StreamWriter sw = new StreamWriter(myCsvFileStream)) {
foreach (ListItem item in this.lstAddEmailAddress.Items) {
sw.WriteLine(" , ," + item.ToString());
}
}
However since myCsvFileStream is not initialized (because stream is a static class) it is always null.
Here is what I do with the data (byte stream) after creating the csv.
byte[] file = new byte[nFileLen];
myCsvFileStream.Read(file, 0, nFileLen);
bool response = this.repositoryService.SaveUsers(this.SelectedAccount.Id, file, this.authenticatedUser.SessionToken.SessionId);
myCsvFileStream.Close();
In the end I used StringBuilder to create my csv file contents. Then got a byte array of its contents and used that to populate my shared stream (I say shared because when the user enters their own CSV file it is a HttpPostedFile but when sending it to our server via the rest call (respositoryservices.saveusers) it uses the same byte stream that it would via this method)
StringBuilder csvFileString = new StringBuilder();
sharedStreamForBatchImport = new MemoryStream();
foreach (ListItem item in this.lstAddEmailAddress.Items) {
csvFileString.Append(",," + item.ToString() + "\\r\\n");
}
//get byte array of the string
byteArrayToBeSent = Encoding.ASCII.GetBytes(csvFileString.ToString());
//set length for read
byteArraySize = (int)csvFileString.Length;
//read bytes into the sharedStreamForBatchImport (byte array)
sharedStreamForBatchImport.Read(byteArrayToBeSent, 0, byteArraySize);
You want to create a new MemoryStream()
Here is a function I use to write CSV files
public static bool WriteCsvFile(string path, StringBuilder stringToWrite)
{
try
{
using (StreamWriter sw = new StreamWriter(path, false)) //false in ordre to overwrite the file if it already exists
{
sw.Write(stringToWrite);
return true;
}
}
catch (Exception)
{
return false;
}
}
stringToWrite is just a string that has been created that way :
public static bool WriteCsvFile(string path, DataTable myData)
{
if (myData == null)
return false;
//Information about the table we read
int nbRows = myData.Rows.Count;
int nbCol = myData.Columns.Count;
StringBuilder stringToWrite = new StringBuilder();
//We get the headers of the table
stringToWrite.Append(myData.Columns[0].ToString());
for (int i = 1; i < nbCol; ++i)
{
stringToWrite.Append(",");
stringToWrite.Append(myData.Columns[i].ToString());
}
stringToWrite.AppendLine();
//We read the rest of the table
for (int i = 0; i < nbRows; ++i)
{
stringToWrite.Append(myData.Rows[i][0].ToString());
for (int j = 1; j < nbCol; ++j)
{
stringToWrite.Append(",");
stringToWrite.Append(myData.Rows[i][j].ToString());
}
stringToWrite.AppendLine();
}
return WriteCsvFile(path, stringToWrite);
}
I need to run some analysis my extracting data from a PDF document.
Using iTextSharp, I used the PdfTextExtractor.GetTextFromPage method to extract contents from a PDF document and it returned me in a single long line.
Is there a way to get the text by line so that i can store them in an array? So that i can analyze the data by line which will be more flexible.
Below is the code I used:
string urlFileName1 = "pdf_link";
PdfReader reader = new PdfReader(urlFileName1);
string text = string.Empty;
for (int page = 1; page <= reader.NumberOfPages; page++)
{
text += PdfTextExtractor.GetTextFromPage(reader, page);
}
reader.Close();
candidate3.Text = text.ToString();
public void ExtractTextFromPdf(string path)
{
using (PdfReader reader = new PdfReader(path))
{
StringBuilder text = new StringBuilder();
ITextExtractionStrategy Strategy = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
string page = "";
page = PdfTextExtractor.GetTextFromPage(reader, i,Strategy);
string[] lines = page.Split('\n');
foreach (string line in lines)
{
MessageBox.Show(line);
}
}
}
}
I know this is posting on an older post, but I spent a lot of time trying to figure this out so I'm going to share this for the future people trying to google this:
using System;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace PDFApp2
{
class Program
{
static void Main(string[] args)
{
string filePath = #"Your said path\the file name.pdf";
string outPath = #"the output said path\the text file name.txt";
int pagesToScan = 2;
string strText = string.Empty;
try
{
PdfReader reader = new PdfReader(filePath);
for (int page = 1; page <= pagesToScan; page ++) //(int page = 1; page <= reader.NumberOfPages; page++) <- for scanning all the pages in A PDF
{
ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
strText = PdfTextExtractor.GetTextFromPage(reader, page, its);
strText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(strText)));
//creating the string array and storing the PDF line by line
string[] lines = strText.Split('\n');
foreach (string line in lines)
{
//Creating and appending to a text file
using (System.IO.StreamWriter file = new System.IO.StreamWriter(outPath, true))
{
file.WriteLine(line);
}
}
}
reader.Close();
}
catch (Exception ex)
{
Console.Write(ex);
}
}
}
}
I had the program read in a PDF, from a set path, and just output to a text file, but you can manipulate that to anything. This was building off of Snziv Gupta's response.
All the other code samples here didn't work for me, probably due to changes to the itext7 API.
This minimal example here works ok:
var pdfReader = new iText.Kernel.Pdf.PdfReader(fileName);
var pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfReader);
var contents = iText.Kernel.Pdf.Canvas.Parser.PdfTextExtractor.GetTextFromPage(pdfDocument.GetFirstPage());
LocationTextExtractionStrategy will automatically insert '\n' in the output text. However, sometimes it will insert '\n' where it shouldn't.
In that case you need to build a custom TextExtractionStrategy or RenderListener. Bascially the code that detects newline is the method
public virtual bool SameLine(ITextChunkLocation other) {
return OrientationMagnitude == other.OrientationMagnitude &&
DistPerpendicular == other.DistPerpendicular;
}
In some cases '\n' shouldn't be inserted if there is only small difference between DistPerpendicular and other.DistPerpendicular, so you need to change it to something like Math.Abs(DistPerpendicular - other.DistPerpendicular) < 10
Or you can put that piece of code in the RenderText method of your custom TextExtractionStrategy/RenderListener class
Use LocationTextExtractionStrategy in lieu of SimpleTextExtractionStrategy. LocationTextExtractionStrategy extracted text contains the new line character at the end of line.
ITextExtractionStrategy Strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), renderFilter);
string pdftext = PdfTextExtractor.GetTextFromPage(reader,pageno, Strategy);
string[] words = pdftext.Split('\n');
return words;
Try
String page = PdfTextExtractor.getTextFromPage(reader, 2);
String s1[]=page.split("\n");