public static void Run() { //ExStart:SaveToDiskWithoutParsing // The path to the File directory. string dataDir = RunExamples.GetDataDir_POP3(); string dstEmail = dataDir + "InsertHeaders.eml"; // Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); // Specify host, username, password, Port and SecurityOptions for your client client.Host = "pop.gmail.com"; client.Username = "******"; client.Password = "******"; client.Port = 995; client.SecurityOptions = SecurityOptions.Auto; try { // Save message to disk by message sequence number client.SaveMessage(1, dstEmail); client.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 "); //ExEnd:SaveToDiskWithoutParsing }
protected void Page_Load(object sender, EventArgs e) { try { using (Pop3Client client = new Pop3Client()) { //Para conectar no servidor do gmail use a porta 995 e SSL client.Connect("pop.gmail.com", 995, true); //Para conectar no servidor do hotmail use a porta 995 e SSL //client.Connect("pop3.live.com", 995, true); //usuário e senha para autenticar client.Authenticate("luisfelipe.lambert", "sakuda5G"); //Pega o número de mensagens int messageCount = client.GetMessageCount(); //Instanciar a lista List<Message> mensagens = new List<Message>(); //Pegar as mensagens for (int i = messageCount; i > 0; i--) { //Adicionar a mensagem a lista mensagens.Add(client.GetMessage(i)); } //Popular o repeater com as mensagens repMensagens.DataSource = mensagens; repMensagens.DataBind(); } } catch (Exception ex) { //Caso ocorra algum erro, uma mensagem será exibida na página litMensagemErro.Text = ex.ToString(); } }
public static void Run() { // ExStart:ParseMessageAndSave // The path to the File directory. string dataDir = RunExamples.GetDataDir_POP3(); // Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); // Specify host, username and password, Port and SecurityOptions for your client client.Host = "pop.gmail.com"; client.Username = "******"; client.Password = "******"; client.Port = 995; client.SecurityOptions = SecurityOptions.Auto; try { // Fetch the message by its sequence number and Save the message using its subject as the file name MailMessage msg = client.FetchMessage(1); msg.Save(dataDir + "first-message_out.eml", SaveOptions.DefaultEml); client.Dispose(); } catch (Exception ex) { Console.WriteLine(Environment.NewLine + ex.Message); } finally { client.Dispose(); } // ExEnd:ParseMessageAndSave Console.WriteLine(Environment.NewLine + "Downloaded email using POP3. Message saved at " + dataDir + "first-message_out.eml"); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_POP3(); string dstEmail = dataDir + "1234.eml"; //Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); //Specify host, username and password for your client client.Host = "pop.gmail.com"; // Set username client.Username = "******"; // Set password client.Password = "******"; // Set the port to 995. This is the SSL port of POP3 server client.Port = 995; // Enable SSL client.SecurityOptions = SecurityOptions.Auto; //Connect and login to a POP3 server try { } catch (Pop3Exception ex) { Console.Write(ex.ToString()); } Console.WriteLine(Environment.NewLine + "Connecting to POP3 server using SSL."); }
protected void brnSendEmail_Click(object sender, EventArgs e) { lblMessage.Text = ""; try { // initialize pop3 client Pop3Client client = new Pop3Client(); client.Host = txtHost.Text; client.Port = int.Parse(txtPort.Text); client.Username = txtUsername.Text; client.Password = txtPassword.Text; // connect to pop3 server and login client.Connect(true); lblMessage.Text = "Successfully connected to POP3 Mail server.<br><hr>"; client.Disconnect(); } catch (Exception ex) { lblMessage.ForeColor = Color.Red; lblMessage.Text = "Error: " + ex.Message; } }
public static void Run() { // ExStart:RetrievingEmailHeaders // Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); // Specify host, username. password, Port and SecurityOptions for your client client.Host = "pop.gmail.com"; client.Username = "******"; client.Password = "******"; client.Port = 995; client.SecurityOptions = SecurityOptions.Auto; try { HeaderCollection headers = client.GetMessageHeaders(1); for (int i = 0; i < headers.Count; i++) { // Display key and value in the header collection Console.Write(headers.Keys[i]); Console.Write(" : "); Console.WriteLine(headers.Get(i)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { client.Dispose(); } // ExEnd:RetrievingEmailHeaders Console.WriteLine(Environment.NewLine + "Displayed header information from emails using POP3 "); }
public static List<MailMessageEx> Receive(string hostname, int port, bool useSsl, string username, string password) { using (Pop3Client client = new Pop3Client(hostname, port, useSsl, username, password)) { client.Trace += new Action<string>(Console.WriteLine); client.Authenticate(); client.Stat(); List<MailMessageEx> maillist = new List<MailMessageEx>(); MailMessageEx message = null; foreach (Pop3ListItem item in client.List()) { message = client.RetrMailMessageEx(item); if (message != null) { client.Dele(item); maillist.Add(message); } } client.Noop(); client.Rset(); client.Quit(); return maillist; } }
public void ConnectOk( ) { Pop3Client pop3Client = new Pop3Client( new PlainMessagesDummyNetworkOperations( ) ); Assert.IsFalse( pop3Client.IsConnected ); pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD" ); Assert.IsTrue( pop3Client.IsConnected ); }
public void StartEmailIndexing() { if (!Directory.Exists(GlobalData.EmailIndexPath)) Directory.CreateDirectory(GlobalData.EmailIndexPath); IndexWriter index; PerFieldAnalyzerWrapper pfaw = new PerFieldAnalyzerWrapper(new KeywordAnalyzer()); pfaw.AddAnalyzer("body", new StopAnalyzer()); try { index = new IndexWriter(GlobalData.EmailIndexPath, pfaw, false); } catch { index = new IndexWriter(GlobalData.EmailIndexPath, pfaw, true); } const string PopServer = "pop.google.in"; const int PopPort = 995; const string User = "******"; const string Pass = "******"; using (Pop3Client client = new Pop3Client(PopServer, PopPort, true, User, Pass)) { client.Trace += new Action<string>(Console.WriteLine); //connects to Pop3 Server, Executes POP3 USER and PASS client.Authenticate(); client.Stat(); foreach (Pop3ListItem item in client.List()) { Document doc = new Document(); MailMessageEx message = client.RetrMailMessageEx(item); doc.Add(new Field("subject", message.Subject.ToLower(), Field.Store.YES, Field.Index.NO_NORMS)); doc.Add(new Field("from", message.From.ToString().ToLower(), Field.Store.YES, Field.Index.NO_NORMS)); doc.Add(new Field("to", message.To.ToString().ToLower(), Field.Store.YES, Field.Index.NO_NORMS)); //doc.Add(new Field("date", message.DeliveryDate.ToLower(), Field.Store.YES, Field.Index.NO_NORMS)); string code = message.Body; code = Regex.Replace(code, @"<\s*head\s*>(.|\n|\r)*?<\s*/\s*head\s*>", " ", RegexOptions.Compiled); //repalce <head> section with single whitespace code = Regex.Replace(code, @"<\s*script (.|\n|\r)*?<\s*/\s*script\s*>", " ", RegexOptions.Compiled);//repalce remaining <script> tags from body with single whitespace code = Regex.Replace(code, @"<!--(.|\n|\r)*?-->", " ", RegexOptions.Compiled); //repalce comments code = Regex.Replace(code, @"<(.|\n|\r)*?>", " ", RegexOptions.Compiled); //repalce all tags with single whitespace code = Regex.Replace(code, @"&.*?;", " ", RegexOptions.Compiled); //replace > e.t.c code = Regex.Replace(code, @"\s+", " ", RegexOptions.Compiled); //replace multiple whitespaces characters by single whitespace code = Regex.Replace(code, @"\ufffd", " ", RegexOptions.Compiled); doc.Add(new Field("body", code.ToLower(), Field.Store.YES, Field.Index.NO_NORMS)); index.AddDocument(doc); } client.Noop(); client.Rset(); client.Quit(); index.Optimize(); index.Close(); } }
public void ConnectFailNotResponse( ) { Mock<INetworkOperations> mockNetworkOperations = new Mock<INetworkOperations>( ); Pop3Client pop3Client = new Pop3Client( mockNetworkOperations.Object ); Assert.IsFalse( pop3Client.IsConnected ); pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD" ); }
protected void gvMessages_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "DisplayMessage") { pnlMessage.Visible = true; string msgSequenceNumber = e.CommandArgument.ToString(); try { // initialize pop3 client Pop3Client client = new Pop3Client(); client.Host = txtHost.Text; client.Port = int.Parse(txtPort.Text); client.Username = txtUsername.Text; client.Password = Session["Password"].ToString(); // SSL settings if (chSSL.Checked == true) { client.EnableSsl = true; client.SecurityMode = Pop3SslSecurityMode.Implicit; } // connect to pop3 server and login client.Connect(true); lblMessage.ForeColor = Color.Green; lblMessage.Text = "Successfully connected to POP3 Mail server.<br><hr>"; // get the message MailMessage msg = client.FetchMessage(int.Parse(msgSequenceNumber)); // sender name and address litFrom.Text = msg.From[0].DisplayName + " <" + msg.From[0].Address + ">"; // to addresses litTo.Text = ""; foreach (MailAddress address in msg.To) { litTo.Text += address.DisplayName + " <" + address.Address + "> , "; } // cc addresses litCc.Text = ""; foreach (MailAddress address in msg.CC) { litCc.Text += address.DisplayName + " <" + address.Address + "> , "; } // subject litSubject.Text = msg.Subject; litBody.Text = msg.HtmlBody; client.Disconnect(); } catch (Exception ex) { lblMessage.ForeColor = Color.Red; lblMessage.Text = "Error: " + ex.Message; } } }
public void ConnectAlreadyConnect( ) { Pop3Client pop3Client = new Pop3Client( new FullMessagesDummyNetworkOperations( ) ); Assert.IsFalse( pop3Client.IsConnected ); pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD", true ); Assert.IsTrue( pop3Client.IsConnected ); pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD", 995, true ); }
public void ConnectFail( ) { Mock<INetworkOperations> mockNetworkOperations = new Mock<INetworkOperations>( ); mockNetworkOperations.Setup( no => no.Read( ) ).Returns( "-ERR" ); Pop3Client pop3Client = new Pop3Client( mockNetworkOperations.Object ); Assert.IsFalse( pop3Client.IsConnected ); pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD", true ); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_POP3(); string dstEmail = dataDir + "message.msg"; //Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); //Specify host, username and password for your client client.Host = "pop.gmail.com"; // Set username client.Username = "******"; // Set password client.Password = "******"; // Set the port to 995. This is the SSL port of POP3 server client.Port = 995; // Enable SSL client.SecurityOptions = SecurityOptions.Auto; try { int messageCount = client.GetMessageCount(); // Create an instance of the MailMessage class MailMessage msg; for (int i = 1; i <= messageCount; i++) { //Retrieve the message in a MailMessage class msg = client.FetchMessage(i); Console.WriteLine("From:" + msg.From.ToString()); Console.WriteLine("Subject:" + msg.Subject); Console.WriteLine(msg.HtmlBody); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { client.Disconnect(); } Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 "); }
private void DownloadFile(string msgSequenceNumber, string format) { try { // initialize pop3 client Pop3Client client = new Pop3Client(); client.Host = txtHost.Text; client.Port = int.Parse(txtPort.Text); client.Username = txtUsername.Text; client.Password = Session["Password"].ToString(); // SSL settings if (chSSL.Checked == true) { client.EnableSsl = true; client.SecurityMode = Pop3SslSecurityMode.Implicit; } // connect to pop3 server and login client.Connect(true); lblMessage.ForeColor = Color.Green; lblMessage.Text = "Successfully connected to POP3 Mail server.<br><hr>"; // get the message MemoryStream stream = new MemoryStream(); MailMessage msg = client.FetchMessage(int.Parse(msgSequenceNumber)); if (format == "eml") msg.Save(stream, MessageFormat.Eml); else msg.Save(stream, MessageFormat.Msg); stream.Position = 0; byte[] msgBytes = new byte[stream.Length]; stream.Read(msgBytes, 0, (int)stream.Length); client.Disconnect(); Response.Clear(); Response.Buffer = true; Response.AddHeader("Content-Length", msgBytes.Length.ToString()); Response.AddHeader("Content-Disposition", "attachment; filename=Message." + format); Response.ContentType = "application/octet-stream"; Response.BinaryWrite(msgBytes); Response.End(); } catch (Exception ex) { lblMessage.ForeColor = Color.Red; lblMessage.Text = "Error: " + ex.Message; } }
public static void Run() { //ExStart:SSLEnabledPOP3Server // Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); // Specify host, username and password, Port and SecurityOptions for your client client.Host = "pop.gmail.com"; client.Username = "******"; client.Password = "******"; client.Port = 995; client.SecurityOptions = SecurityOptions.Auto; Console.WriteLine(Environment.NewLine + "Connecting to POP3 server using SSL."); //ExEnd:SSLEnabledPOP3Server }
public static void Run() { // ExStart:GetServerExtensionsUsingPop3Client // Connect and log in to POP3 Pop3Client client = new Pop3Client("pop.gmail.com", "username", "password"); client.SecurityOptions = SecurityOptions.Auto; client.Port = 993; string[] getCaps = client.GetCapabilities(); foreach (string item in getCaps) { Console.WriteLine(item); } // ExEnd:GetServerExtensionsUsingPop3Client }
protected void brnSendEmail_Click(object sender, EventArgs e) { lblMessage.Text = ""; try { // initialize pop3 client Pop3Client client = new Pop3Client(); client.Host = txtHost.Text; client.Port = int.Parse(txtPort.Text); client.Username = txtUsername.Text; client.Password = txtPassword.Text; // SSL settings if (chSSL.Checked == true) { client.EnableSsl = true; client.SecurityMode = Pop3SslSecurityMode.Implicit; } // connect to pop3 server and login client.Connect(true); lblMessage.ForeColor = Color.Green; lblMessage.Text = "Successfully connected to SSL enabled POP3 Mail server.<br><hr>"; // get mailbox information Pop3MailboxInfo mailboxInfo = client.GetMailboxInfo(); long nMailboxSize = mailboxInfo.OccupiedSize; string strMailboxSize = ""; // convert size in easy to read format if (nMailboxSize <= 1024) strMailboxSize = nMailboxSize.ToString() + " bytes"; else if (nMailboxSize > 1024 && nMailboxSize <= (1024 * 1024)) strMailboxSize = nMailboxSize.ToString() + " bytes (approx " + Math.Round((double)nMailboxSize / 1024, 2).ToString() + " KB)"; else strMailboxSize = nMailboxSize.ToString() + " bytes (approx " + Math.Round((double)nMailboxSize / (1024 * 1024), 2).ToString() + " MB)"; lblMailboxSize.Text = strMailboxSize; lblMessageCount.Text = mailboxInfo.MessageCount.ToString() + " messages found"; client.Disconnect(); } catch (Exception ex) { lblMessage.ForeColor = Color.Red; lblMessage.Text = "Error: " + ex.Message; } }
public static void Run() { // ExStart:RetrieveMessageSummaryInformationUsingUniqueId string uniqueId = "unique id of a message from server"; Pop3Client client = new Pop3Client("host.domain.com", 456, "username", "password"); client.SecurityOptions = SecurityOptions.Auto; Pop3MessageInfo messageInfo = client.GetMessageInfo(uniqueId); if (messageInfo != null) { Console.WriteLine(messageInfo.Subject); Console.WriteLine(messageInfo.Date); } // ExEnd:RetrieveMessageSummaryInformationUsingUniqueId }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_POP3(); string dstEmail = dataDir + "message.msg"; //Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); //Specify host, username and password for your client client.Host = "pop.gmail.com"; // Set username client.Username = "******"; // Set password client.Password = "******"; // Set the port to 995. This is the SSL port of POP3 server client.Port = 995; // Enable SSL client.SecurityOptions = SecurityOptions.Auto; try { HeaderCollection headers = client.GetMessageHeaders(1); for (int i = 0; i < headers.Count; i++) { // Display key and value in the header collection Console.Write(headers.Keys[i]); Console.Write(" : "); Console.WriteLine(headers.Get(i)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { client.Disconnect(); } Console.WriteLine(Environment.NewLine + "Displayed header information from emails using POP3 "); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_POP3(); string dstEmail = dataDir + "first-message.eml"; //Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); //Specify host, username and password for your client client.Host = "pop.gmail.com"; // Set username client.Username = "******"; // Set password client.Password = "******"; // Set the port to 995. This is the SSL port of POP3 server client.Port = 995; // Enable SSL client.SecurityOptions = SecurityOptions.Auto; try { //Fetch the message by its sequence number MailMessage msg = client.FetchMessage(1); //Save the message using its subject as the file name msg.Save(dstEmail, Aspose.Email.Mail.SaveOptions.DefaultEml); client.Disconnect(); } catch (Exception ex) { Console.WriteLine(Environment.NewLine + ex.Message); } finally { client.Disconnect(); } Console.WriteLine(Environment.NewLine + "Downloaded email using POP3. Message saved at " + dstEmail); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_POP3(); string dstEmail = dataDir + "1234.eml"; //Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); //Specify host, username and password for your client client.Host = "pop.gmail.com"; // Set username client.Username = "******"; // Set password client.Password = "******"; // Set the port to 995. This is the SSL port of POP3 server client.Port = 995; // Enable SSL client.SecurityOptions = SecurityOptions.Auto; // Get the size of the mailbox long nSize = client.GetMailboxSize(); Console.WriteLine("Mailbox size is " + nSize + " bytes."); // Get mailbox info Aspose.Email.Pop3.Pop3MailboxInfo info = client.GetMailboxInfo(); // Get the number of messages in the mailbox int nMessageCount = info.MessageCount; Console.WriteLine("Number of messages in mailbox are " + nMessageCount); // Get occupied size long nOccupiedSize = info.OccupiedSize; Console.WriteLine("Occupied size is " + nOccupiedSize); Console.WriteLine(Environment.NewLine + "Getting the mailbox information of POP3 server."); }
public Dictionary<string, string> GetEmailByMessageId(string messageId, DateTime? data, string host, int port, string username, string password) { try { var client = new Pop3Client(host, port, username, password); //var builder = new MailQueryBuilder(); //builder.InternalDate.Since(data); //var query = builder.GetQuery(); //// Get list of messages //var messages = client.ListMessages(query); var messages = client.ListMessages(); var result = new Dictionary<string, string>(messages.Count); foreach (var message in messages) { using (var stream = new MemoryStream()) { client.SaveMessage(message.SequenceNumber, stream); var emlMessage = Conversione.ToString(stream); if (!string.IsNullOrEmpty(messageId) && emlMessage.Contains(messageId)) result.Add(message.UniqueId, emlMessage); else result.Add(message.UniqueId, emlMessage); } } // Disconnect from POP3 client.Disconnect(); return result; } catch (Pop3Exception ex) { _log.DebugFormat("Errore nella lettura delle ricevute email - {0} - messageId:{1} - data:{2} - host:{3} - port:{4} - username:{5} - password:{6}", ex, Utility.GetMethodDescription(), messageId, data, host, port, username, password); return new Dictionary<string, string>(); } catch (Exception ex) { _log.ErrorFormat("Errore nella lettura delle ricevute email - {0} - messageId:{1} - data:{2} - host:{3} - port:{4} - username:{5} - password:{6}", ex, Utility.GetMethodDescription(), messageId, data, host, port, username, password); return new Dictionary<string, string>(); } }
public static void Run() { // ExStart:FilterMessagesFromPOP3Mailbox // Connect and log in to POP3 const string host = "host"; const int port = 110; const string username = "******"; const string password = "******"; Pop3Client client = new Pop3Client(host, port, username, password); // Set conditions, Subject contains "Newsletter", Emails that arrived today MailQueryBuilder builder = new MailQueryBuilder(); builder.Subject.Contains("Newsletter"); builder.InternalDate.On(DateTime.Now); // Build the query and Get list of messages MailQuery query = builder.GetQuery(); Pop3MessageInfoCollection messages = client.ListMessages(query); Console.WriteLine("Pop3: " + messages.Count + " message(s) found."); // ExEnd:FilterMessagesFromPOP3Mailbox }
public static void GetMessages( string server, string userName, string password, bool useSsl ) { try { Pop3Client pop3Client = new Pop3Client( ); Console.WriteLine( "Connecting to POP3 server '{0}'...{1}", server, Environment.NewLine ); pop3Client.Connect( server, userName, password, useSsl ); Console.WriteLine( "List Messages...{0}", Environment.NewLine ); IEnumerable<Pop3Message> messages = pop3Client.List( ); Console.WriteLine( "Retrieve Messages...{0}", Environment.NewLine ); foreach ( Pop3Message message in messages ) { Console.WriteLine( "- Number: {0}", message.Number ); pop3Client.Retrieve( message ); Console.WriteLine( "\t* MessageId: {0}", message.MessageId ); Console.WriteLine( "\t* Date: {0}", message.Date ); Console.WriteLine( "\t* From: {0}", message.From ); Console.WriteLine( "\t* To: {0}", message.To ); Console.WriteLine( "\t* Subject: {0}", message.Subject ); Console.WriteLine( "\t* Body Length: {0}", message.Body.Length ); Console.WriteLine( ); } Console.WriteLine( "Disconnecting...{0}", Environment.NewLine ); pop3Client.Disconnect( ); } catch ( Exception ex ) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine( ex.Message ); Console.ForegroundColor = ConsoleColor.White; } }
private void fromPop3Button_Click(object sender, EventArgs e) { Pop3Client pop3Client = new Pop3Client(); pop3Client.ShowDialog(); try { this.currentStatusTextbox.Text = "Querying..."; CtchResponse response = CtchClient.QueryServer(this.hostTextBox.Text, Convert.ToInt32(this.portNumericUpDown.Value), pop3Client._selectedMessage); this.spamClassificationTextbox.Text = response.SpamClassification.ToString(); this.vodClassificationTextbox.Text = response.VodClassification.ToString(); this.flagTextbox.Text = response.CtchFlag; this.refIdTextbox.Text = response.RefID; this.currentStatusTextbox.Text = string.Format("Done. Last query: {0}", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()); } catch (Exception ex) { MessageBox.Show(string.Format("Error while contacting server. Please verify it is running\r\n{0}", ex.ToString())); } }
private void ListMessages() { lblMessage.Text = ""; lblMessage.ForeColor = Color.Green; try { // initialize pop3 client Pop3Client client = new Pop3Client(); client.Host = txtHost.Text; client.Port = int.Parse(txtPort.Text); client.Username = txtUsername.Text; client.Password = Session["Password"].ToString(); // SSL settings if (chSSL.Checked == true) { client.EnableSsl = true; client.SecurityMode = Pop3SslSecurityMode.Implicit; } // connect to pop3 server and login client.Connect(true); lblMessage.ForeColor = Color.Green; lblMessage.Text = "Successfully connected to SSL enabled POP3 Mail server.<br><hr>"; // get list of messages Pop3MessageInfoCollection msgCollection = client.ListMessages(); gvMessages.DataSource = msgCollection; gvMessages.DataBind(); client.Disconnect(); } catch (Exception ex) { lblMessage.ForeColor = Color.Red; lblMessage.Text = "Error: " + ex.Message; } }
public static async Task GetMessagesAsync( string server, string userName, string password, bool useSsl ) { try { Pop3Client pop3Client = new Pop3Client( ); Console.WriteLine( "Connecting to POP3 server '{0}'...{1}", server, Environment.NewLine ); await pop3Client.ConnectAsync( server, userName, password, useSsl ); Console.WriteLine( "List and Retrieve Messages...{0}", Environment.NewLine ); IEnumerable<Pop3Message> messages = await pop3Client.ListAndRetrieveAsync( ); foreach ( Pop3Message message in messages ) { Console.WriteLine( "- Number: {0}", message.Number ); Console.WriteLine( "\t* MessageId: {0}", message.MessageId ); Console.WriteLine( "\t* Date: {0}", message.Date ); Console.WriteLine( "\t* From: {0}", message.From ); Console.WriteLine( "\t* To: {0}", message.To ); Console.WriteLine( "\t* Subject: {0}", message.Subject ); Console.WriteLine( "\t* Retrieved: {0}", message.Retrieved ); Console.WriteLine( "\t* Body Length: {0}", message.Body.Length ); Console.WriteLine( "\t* Attachments Count: {0}", ((List<Pop3Attachment>)message.Attachments).Count ); Console.WriteLine( ); } Console.WriteLine( "Disconnecting...{0}", Environment.NewLine ); await pop3Client.DisconnectAsync( ); } catch ( Exception ex ) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine( ex.Message ); Console.ForegroundColor = ConsoleColor.White; } }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_POP3(); string dstEmail = dataDir + "1234.eml"; //Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); //Specify host, username and password for your client client.Host = "pop.gmail.com"; // Set username client.Username = "******"; // Set password client.Password = "******"; // Set the port to 995. This is the SSL port of POP3 server client.Port = 995; // Enable SSL client.SecurityOptions = SecurityOptions.Auto; try { //Save message to disk by message sequence number client.SaveMessage(1, dstEmail); client.Disconnect(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 "); }
public static void Run() { // Create an instance of the Pop3Client class //ExStart:GettingMailboxInfo Pop3Client client = new Pop3Client(); // Specify host, username, password, Port and SecurityOptions for your client client.Host = "pop.gmail.com"; client.Username = "******"; client.Password = "******"; client.Port = 995; client.SecurityOptions = SecurityOptions.Auto; // Get the size of the mailbox, Get mailbox info, number of messages in the mailbox long nSize = client.GetMailboxSize(); Console.WriteLine("Mailbox size is " + nSize + " bytes."); Pop3MailboxInfo info = client.GetMailboxInfo(); int nMessageCount = info.MessageCount; Console.WriteLine("Number of messages in mailbox are " + nMessageCount); long nOccupiedSize = info.OccupiedSize; Console.WriteLine("Occupied size is " + nOccupiedSize); //ExEnd:GettingMailboxInfo Console.WriteLine(Environment.NewLine + "Getting the mailbox information of POP3 server."); }
/// <summary> /// Read new incoming mail /// </summary> public void ReadIncomingEmail() { while (true) { // The client disconnects from the server when being disposed using (Pop3Client clientTest = new Pop3Client()) { Authenticate(clientTest); //Authenticate POP client int NewEmailCount = 0; //Number of new emails int CurrentEmailCount = clientTest.GetMessageCount(); //Current number of emails in inbox string EmailFrom = string.Empty; //Sender of mail //New mail arrived if (CommonProperty.GlobalEmailCount < CurrentEmailCount) { //Number of new emails NewEmailCount = CurrentEmailCount - CommonProperty.GlobalEmailCount; //Stores all new mails List <Message> allMessages = new List <Message>(NewEmailCount); //Fetch details of all new mail for (int i = CommonProperty.GlobalEmailCount + 1; i <= CurrentEmailCount; i++) { allMessages.Add(clientTest.GetMessage(i)); } try { foreach (var mail in allMessages) { CommonProperty.TicketDetail.CreatedOn = DateTime.Now; //Date of receiving email EmailFrom = mail.Headers.From.Address; //Sender of mail CommonProperty.TicketDetail.Title = mail.Headers.Subject; //Subject of mail //Body contains plain text if (mail.FindFirstPlainTextVersion() != null) { CommonProperty.TicketDetail.Description = mail.FindFirstPlainTextVersion().GetBodyAsText(); } //Body contains HTML else { CommonProperty.TicketDetail.Description = mail.FindFirstHtmlVersion().GetBodyAsText(); } //Checks subject of mail. If ticket is generated no new ticket generation if (CommonProperty.TicketDetail.Title.Contains("RequestID:##")) { ExistTicketEntry(EmailFrom, CommonProperty.TicketDetail.Title); //Keeps log of communication for ticket } else { GenerateTicket(EmailFrom); //New ticket generation } } } catch (Exception ex) { StreamWriter sw = new StreamWriter(CommonProperty.EmailErrorLogFilePath, true); sw.WriteLine(ex.ToString()); sw.Flush(); sw.Close(); } //CommonProperty.GlobalEmailCount = CurrentEmailCount; //Update global mail count to latest value allMessages.Clear(); //Clears list } Thread.Sleep(2000); //Wait for 2 sec CommonProperty.GlobalEmailCount = clientTest.GetMessageCount(); //Update global mail count to latest value } } }
public void Connect(string hostname, string username, string password, int port, bool isUseSsl) { this._client = new Pop3Client(); this._client.Connect(hostname, port, isUseSsl); this._client.Authenticate(username, password); }
/// <summary> /// Execute() implementation /// </summary> /// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public void Execute(XmlNode testConfig, Context context) { int delayBeforeCheck = context.ReadConfigAsInt32(testConfig, "DelayBeforeCheck", true); string server = context.ReadConfigAsString(testConfig, "Server"); string user = context.ReadConfigAsString(testConfig, "User"); string password = context.ReadConfigAsString(testConfig, "Password"); string from = null; bool showBody = false; string subject = null; int attachments = -1; bool found = false; if (testConfig.SelectSingleNode("ShowBody") != null) { showBody = context.ReadConfigAsBool(testConfig, "ShowBody"); } if (testConfig.SelectSingleNode("From") != null) { from = context.ReadConfigAsString(testConfig, "From"); } if (testConfig.SelectSingleNode("Subject") != null) { subject = context.ReadConfigAsString(testConfig, "Subject"); } if (testConfig.SelectSingleNode("Attachments") != null) { attachments = context.ReadConfigAsInt32(testConfig, "Attachments"); } if (delayBeforeCheck > 0) { context.LogInfo("Waiting for {0} seconds before checking the mail.", delayBeforeCheck); System.Threading.Thread.Sleep(delayBeforeCheck * 1000); } var email = new Pop3Client(user, password, server); email.OpenInbox(); try { while (email.NextEmail()) { if (email.To == user && (email.From == from || from == null) && (email.Subject == subject || subject == null)) { if (attachments > 0 && email.IsMultipart) { int a = 0; IEnumerator enumerator = email.MultipartEnumerator; while (enumerator.MoveNext()) { var multipart = (Pop3Component) enumerator.Current; if (multipart.IsBody) { if (showBody) { context.LogData("Multipart body", multipart.Data); } } else { context.LogData("Attachment name", multipart.Name); a++; } } if (attachments == a) { found = true; break; } } else { if (showBody) { context.LogData("Single body", email.Body); } found = true; break; } } } if (!found) { throw new Exception("Failed to find email message"); } else { email.DeleteEmail(); } } finally { email.CloseConnection(); } }
/// <summary> /// Exports FAMOUS BRANDS Campaign Purchases to Clientele using SFTP /// </summary> /// <param name="writer"></param> /// <returns></returns> public static bool Import(StreamWriter writer) { try { if (!ConfigSettings.SystemRules.DisputeMonitorEnabled) { Info(writer, $" Extract of Disputes is disabled by Admin. RETURNING @{DateTime.Now}"); return(true); } using (PSPConfigService cpservice = new PSPConfigService()) { List <PSPConfig> configs = cpservice.List()?.Where(pc => !string.IsNullOrWhiteSpace(pc.ImportEmailHost) && !string.IsNullOrWhiteSpace(pc.ImportEmailPassword) && !string.IsNullOrWhiteSpace(pc.ImportEmailUsername) )?.ToList(); if (!configs.NullableAny()) { Info(writer, $" *** There are no PSPs with correctly setup Email Settings to extract Email Disputes. Returning @ {DateTime.Now}"); return(true); } Info(writer, $" BEGIN: Dispute Extract for {configs.Count} PSPs... @{DateTime.Now}"); foreach (PSPConfig p in configs) { if (p.ImportEmailHost.ToLower().Contains("pop")) { #region Pop3 Client using (Pop3Client client = new Pop3Client()) { Info(writer, $" - Connecting to Server [{p.ImportEmailHost}] for {p.PSP.CompanyName} using POP3 Client... @{DateTime.Now}"); client.Connect(p.ImportEmailHost?.Trim(), p.ImportEmailPort ?? 110, p.ImportUseSSL ?? false); Info(writer, $" - Authenticating with CREDENTIALS: {p.ImportEmailUsername}, **** using POP3 Client... @{DateTime.Now}"); client.Authenticate(p.ImportEmailUsername, p.ImportEmailPassword); int count = 1; for (int i = 0; i < client.Count; i++) { MimeMessage message = client.GetMessage(i); CreateDispute(writer, message, count); count++; DisputeMonitorCount += 1; } client.Disconnect(true); } #endregion } else if (p.ImportEmailHost.ToLower().Contains("imap")) { #region Imap Client using (ImapClient client = new ImapClient()) { Info(writer, $" - Connecting to Server [{p.ImportEmailHost}] for {p.PSP.CompanyName} using Imap Client... @{DateTime.Now}"); client.Connect(p.ImportEmailHost?.Trim(), p.ImportEmailPort ?? 993, p.ImportUseSSL ?? true); Info(writer, $" - Authenticating with CREDENTIALS: {p.ImportEmailUsername}, **** using Imap Client... @{DateTime.Now}"); client.Authenticate(p.ImportEmailUsername, p.ImportEmailPassword); IMailFolder inbox = client.Inbox; inbox.Open(FolderAccess.ReadOnly); int count = 1; for (int i = 0; i < inbox.Count; i++) { MimeMessage message = inbox.GetMessage(i); CreateDispute(writer, message, count); count++; DisputeMonitorCount += 1; } client.Disconnect(true); } #endregion } } Info(writer, $" END: Dispute Extract for {configs.Count} PSPs... @{DateTime.Now}"); } } catch (Exception ex) { Error(writer, ex, "Export"); return(false); } return(true); }
/// <summary> /// 获取邮件 /// </summary> public void MailPop3Client() { //Logger.Log.Info("邮件审批开始..."); //Logger.Log.Info("************************---PopServer=" + PopServer); //Logger.Log.Debug("************************---PopPort=" + PopPort); //Logger.Log.Debug("************************---User="******"************************---Pass="******"************************---UseSSL=" + UseSSL); using (Pop3Client client = new Pop3Client(PopServer, PopPort, UseSSL, User, Pass)) { //显示程序与POP3服务器的通信过程 //client.Trace += new Action<string>(Console.WriteLine); //连接POP3服务器并验证用户身份 Logger.Log.Info("Connect POP3 Server and verify..."); client.Authenticate(); Logger.Log.Info("Verify Success..."); client.Stat(); //枚举所有未读邮件 Logger.Log.Info("Mail Exist..." + client.List()); //SpreadtrumLHDEntities Db = new SpreadtrumLHDEntities(); DbOperation dbo = new DbOperation(); foreach (Pop3ListItem item in client.List()) { MailMessageEx message = null; try { LOTSImportSDLogs lotlogs = new LOTSImportSDLogs(); Logger.Log.Info("RetrMailMessageEx item=" + item.MessageId); message = client.RetrMailMessageEx(item); if (message.Subject.ToLower().StartsWith("[lot judgement]") //&& message.Sender.Address.ToLower() == "*****@*****.**" ) { Logger.Log.Info("RetrMailMessageEx message subject=" + message.Subject); string[] data = getLotData(message.Subject); Logger.Log.Info("RetrMailMessageEx message osat=" + data[2]); Logger.Log.Info("RetrMailMessageEx message Device=" + data[3]); Logger.Log.Info("RetrMailMessageEx message LotNO=" + data[4]); Logger.Log.Info("RetrMailMessageEx message Stage=" + data[5]); Logger.Log.Info("RetrMailMessageEx message DeliveryDate=" + message.DeliveryDate.ToString()); //lotlogs.OSAT = data[2]; //lotlogs.Device = data[3]; //lotlogs.LotNO = data[4]; //lotlogs.Stage = data[5]; //lotlogs.DeliveryDate = message.DeliveryDate; //lotlogs.CreateTime = DateTime.Now; //lotlogs.LHDFormatStatus = "Pending"; //lotlogs.LHDImportStatus = "Pending"; //Db.LOTSImportSDLogs.Add(lotlogs); string insertSQL = @"INSERT INTO [dbo].[LOTSImportSDLogs] ([OSAT] ,[Device] ,[LotNO] ,[Stage] ,[DeliveryDate] ,[CreateTime] ,[LHDFormatStatus] ,[LHDImportStatus]) VALUES ('{0}' ,'{1}' ,'{2}' ,'{3}' ,'{4}' ,GETDATE() ,'Pending' ,'Pending');"; //Db.Set<LOTSImportSDLogs>().Attach(lotlogs); //Db.Entry(lotlogs).State = EntityState.Added; dbo.ExecuteNonQuery(string.Format(insertSQL, data[2], data[3], data[4], data[5], message.DeliveryDate.ToString("yyyy-MM-dd HH:mm:ss"))); } client.Dele(item); } catch (Exception ex) { Logger.Log.Error("RetrMailMessageEx error=" + ex); //client.Dele(item); continue; } } //Db.SaveChanges(); Logger.Log.Info("邮件处理完毕。"); client.Quit(); } }
private SortedList <string, Rfc822Message> getSmtpMessages() { Pop3Client target = new Pop3Client(); target.Host = Host; //TCP port for connection target.Port = Convert.ToUInt16(Port); //Username to login to the POP3 server target.Username = Username; //Password to login to the POP3 server target.Password = Password; // SSL Interaction type Email.Net.Common.Configurations.EInteractionType interaction = default(Email.Net.Common.Configurations.EInteractionType); if (TSL) { interaction = EInteractionType.StartTLS; } else if (SSL) { interaction = EInteractionType.SSLPort; } else { interaction = EInteractionType.Plain; } target.SSLInteractionType = EInteractionType.SSLPort; target.AuthenticationType = EAuthenticationType.Login; if (authenticationType == (int)EAuthenticationType.None) { Password = ""; Username = ""; } System.Collections.Generic.SortedList <string, Rfc822Message> messages = new System.Collections.Generic.SortedList <string, Rfc822Message>(); Rfc822Message msg = null; // Login to POP server try { Pop3Response response = target.Login(); if (response.Type == EPop3ResponseType.OK) { // Retrieve Unique IDs for all messages Pop3MessageUIDInfoCollection messageUIDs = target.GetAllUIDMessages(); //Check if messages already received foreach (Pop3MessageUIDInfo uidInfo in messageUIDs) { try { msg = target.GetMessage(uidInfo.SerialNumber); } catch (Email.Net.Common.Exceptions.ConnectionException ex) { } catch (Email.Net.Common.Exceptions.AuthenticationMethodNotSupportedException ex) { } catch (System.Exception ex) { } if ((msg != null)) { if (!string.IsNullOrEmpty(UtilFunctions.findIssueTag(msg).Trim())) { if (!UtilFunctions.searchUID(uidInfo.UniqueNumber)) { // No. Add to list messages.Add(uidInfo.UniqueNumber, target.GetMessage(uidInfo.SerialNumber)); } } } if (!runFlag | !isEnabled) { break; // TODO: might not be correct. Was : Exit For } } string cnt = (messages.Count.ToString()); cnt += " SMTP messages were found"; GlobalShared.Log.Log((int)LogClass.logType.Info, cnt, false); } //Logout from the server target.Logout(); } catch (IOException ex) { GlobalShared.Log.Log((int)LogClass.logType.ErrorCondition, ex.Message, false); } catch (Email.Net.Common.Exceptions.ConnectionException ex) { GlobalShared.Log.Log((int)LogClass.logType.ErrorCondition, ex.Message, false); } catch (System.Exception ex) { GlobalShared.Log.Log((int)LogClass.logType.ErrorCondition, ex.Message, false); } return(messages); }
protected void ButtonSearch_Click(object sender, EventArgs e) { try { Class1 class1 = new Class1(); SqlConnection con2 = new SqlConnection(class1.conn); con2.Open(); SqlCommand com1 = new SqlCommand("select email from screenshots where empid='" + Convert.ToString(TextBox3.Text) + "'", con2); SqlDataReader sdr1; sdr1 = com1.ExecuteReader(); sdr1.Read(); if (sdr1.FieldCount > 0) { var client = new Pop3Client(); client.Connect("pop.gmail.com", 995, true); client.Authenticate(email1, Convert.ToString(TextBox4.Text)); var count = client.GetMessageCount(); for (int i = count; i >= (count - 10); i--) { Message message = client.GetMessage(i); String from = Convert.ToString(message.Headers.From.Address); if (from.Equals(sdr1[0])) { String pathString = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Convert.ToString(TextBox3.Text)); List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { String filename = attachment.FileName; byte[] Content = attachment.Body; MemoryStream ms = new MemoryStream(Content); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); String path1 = pathString + "\\" + filename; img.Save(path1); SqlConnection con4 = new SqlConnection(class1.conn); con4.Open(); try { SqlCommand com = new SqlCommand("insert into images values ('" + Convert.ToString(TextBox3.Text) + "/" + filename + "', '" + Convert.ToString(TextBox3.Text) + "')", con4); int i1 = com.ExecuteNonQuery(); } catch (Exception) { func3(); } con4.Close(); } } } con2.Close(); func3(); } } catch (Exception) { func3(); Label3.Visible = true; Label3.Text = ""; } }
/// <summary> /// Récupère les nouveaux Messaegs du serveur de Mails POP3 dont les informations de /// connextion sont indiqués dans le paramètre /// </summary> /// <param name="parametre">Parametres de connexion au serveur de mails POP3</param> /// <returns>Le Data du Result contient un liste de MailMessageEx</returns> public CResultAErreur RetrieveMails(CCompteMail compteMail) { CResultAErreur result = CResultAErreur.True; if (compteMail == null) { result.EmpileErreur("Erreur dans CRecepteurMail: compteMail est nul"); } m_compteMail = compteMail; m_compteMail.BeginEdit(); m_compteMail.DateDernierReleve = DateTime.Now; CParametreCompteMail parametre = compteMail.ParametreCompteMail; if (parametre == null) { result.EmpileErreur("Erreur dans CRecepteurMail: Le ¨Parametre de compte est nul"); return(result); } using (Pop3Client client = new Pop3Client()) { try { client.Connect(parametre.PopServer, parametre.PopPort, parametre.UseSsl); // Authenticate ourselves towards the server client.Authenticate(parametre.User, parametre.Password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. for (int i = 1; i <= messageCount; i++) { MessageHeader messageHead = client.GetMessageHeaders(i); Message messageRecu = null; CTracabiliteMail traceMail = new CTracabiliteMail(m_compteMail.ContexteDonnee); CFiltreData filtreIfExist = new CFiltreData( CTracabiliteMail.c_champMessageUid + " = @1 and " + CCompteMail.c_champId + " = @2 ", messageHead.MessageId, compteMail.Id); if (!traceMail.ReadIfExists(filtreIfExist)) { try { C2iMail mail = new C2iMail(compteMail.ContexteDonnee); mail.CreateNewInCurrentContexte(); mail.CompteMail = m_compteMail; if (parametre.HeaderOnly) { mail.FillFromHeader(messageHead); } else { messageRecu = client.GetMessage(i); mail.FillFromMessage(messageRecu); } } catch (Exception ex) { result.EmpileErreur(ex.Message); } } if (parametre.SupprimerDuServeur) { if (parametre.DelaiSuppression <= 0) { client.DeleteMessage(i); } else { DateTime dateMessage = messageHead.DateSent; TimeSpan dureeDeVie = DateTime.Now - dateMessage; if (dureeDeVie.Days >= parametre.DelaiSuppression) { client.DeleteMessage(i); } } } } } catch (Exception exception) { result.EmpileErreur(exception.Message); } finally { client.Disconnect(); } } if (!result) { m_compteMail.LastErreur = result.MessageErreur; } else { m_compteMail.LastErreur = I.T("Mails succesfully retrived|10000"); } result += m_compteMail.CommitEdit(); return(result); }
public POP3ReadTelecom(TaskInfo info) : base(info) { telecom = new Pop3Client(TaskInfo["Host"], TaskInfo["Login"], TaskInfo.GetPassword(), TaskInfo.Get("Port", 21), TaskInfo.Get("UseSSL", false), TaskInfo.Get("Timeout", 60000)); }
public async void TestLangExtension() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "lang.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "lang.capa1.txt")); commands.Add(new Pop3ReplayCommand("UTF8\r\n", "lang.utf8.txt")); commands.Add(new Pop3ReplayCommand("APOP username d99894e8445daf54c4ce781ef21331b7\r\n", "lang.auth.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "lang.capa2.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "lang.stat.txt")); commands.Add(new Pop3ReplayCommand("LANG\r\n", "lang.getlang.txt")); commands.Add(new Pop3ReplayCommand("LANG en\r\n", "lang.setlang.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "gmail.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(LangCapa1, client.Capabilities); Assert.AreEqual(2, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH2"), "Expected SASL XOAUTH2 auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); try { await client.EnableUTF8Async(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in EnableUTF8: {0}", ex); } // Note: remove the XOAUTH2 auth mechanism to force PLAIN auth client.AuthenticationMechanisms.Remove("XOAUTH2"); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(LangCapa2, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(3, client.Count, "Expected 3 messages"); var languages = await client.GetLanguagesAsync(); Assert.AreEqual(6, languages.Count); Assert.AreEqual("en", languages[0].Language); Assert.AreEqual("English", languages[0].Description); Assert.AreEqual("en-boont", languages[1].Language); Assert.AreEqual("English Boontling dialect", languages[1].Description); Assert.AreEqual("de", languages[2].Language); Assert.AreEqual("Deutsch", languages[2].Description); Assert.AreEqual("it", languages[3].Language); Assert.AreEqual("Italiano", languages[3].Description); Assert.AreEqual("es", languages[4].Language); Assert.AreEqual("Espanol", languages[4].Description); Assert.AreEqual("sv", languages[5].Language); Assert.AreEqual("Svenska", languages[5].Description); await client.SetLanguageAsync("en"); try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public async void TestGMailPop3Client() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "gmail.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "gmail.capa1.txt")); commands.Add(new Pop3ReplayCommand("AUTH PLAIN\r\n", "gmail.plus.txt")); commands.Add(new Pop3ReplayCommand("AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "gmail.auth.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "gmail.capa2.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "gmail.stat.txt")); commands.Add(new Pop3ReplayCommand("UIDL\r\n", "gmail.uidl.txt")); commands.Add(new Pop3ReplayCommand("UIDL 1\r\n", "gmail.uidl1.txt")); commands.Add(new Pop3ReplayCommand("UIDL 2\r\n", "gmail.uidl2.txt")); commands.Add(new Pop3ReplayCommand("UIDL 3\r\n", "gmail.uidl3.txt")); commands.Add(new Pop3ReplayCommand("LIST\r\n", "gmail.list.txt")); commands.Add(new Pop3ReplayCommand("LIST 1\r\n", "gmail.list1.txt")); commands.Add(new Pop3ReplayCommand("LIST 2\r\n", "gmail.list2.txt")); commands.Add(new Pop3ReplayCommand("LIST 3\r\n", "gmail.list3.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "gmail.retr1.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt")); commands.Add(new Pop3ReplayCommand("TOP 1 0\r\n", "gmail.top.txt")); commands.Add(new Pop3ReplayCommand("TOP 1 0\r\nTOP 2 0\r\nTOP 3 0\r\n", "gmail.top123.txt")); commands.Add(new Pop3ReplayCommand("TOP 1 0\r\nTOP 2 0\r\nTOP 3 0\r\n", "gmail.top123.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "gmail.retr1.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt")); commands.Add(new Pop3ReplayCommand("NOOP\r\n", "gmail.noop.txt")); commands.Add(new Pop3ReplayCommand("DELE 1\r\n", "gmail.dele.txt")); commands.Add(new Pop3ReplayCommand("RSET\r\n", "gmail.rset.txt")); commands.Add(new Pop3ReplayCommand("DELE 1\r\nDELE 2\r\nDELE 3\r\n", "gmail.dele123.txt")); commands.Add(new Pop3ReplayCommand("RSET\r\n", "gmail.rset.txt")); commands.Add(new Pop3ReplayCommand("DELE 1\r\nDELE 2\r\nDELE 3\r\n", "gmail.dele123.txt")); commands.Add(new Pop3ReplayCommand("RSET\r\n", "gmail.rset.txt")); commands.Add(new Pop3ReplayCommand("DELE 1\r\nDELE 2\r\nDELE 3\r\n", "gmail.dele123.txt")); commands.Add(new Pop3ReplayCommand("RSET\r\n", "gmail.rset.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "gmail.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(GMailCapa1, client.Capabilities); Assert.AreEqual(2, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH2"), "Expected SASL XOAUTH2 auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); // Note: remove the XOAUTH2 auth mechanism to force PLAIN auth client.AuthenticationMechanisms.Remove("XOAUTH2"); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(GMailCapa2, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(3, client.Count, "Expected 3 messages"); var uids = await client.GetMessageUidsAsync(); Assert.AreEqual(3, uids.Count); Assert.AreEqual("101", uids[0]); Assert.AreEqual("102", uids[1]); Assert.AreEqual("103", uids[2]); for (int i = 0; i < 3; i++) { var uid = await client.GetMessageUidAsync(i); Assert.AreEqual(uids[i], uid); } var sizes = await client.GetMessageSizesAsync(); Assert.AreEqual(3, sizes.Count); Assert.AreEqual(1024, sizes[0]); Assert.AreEqual(1025, sizes[1]); Assert.AreEqual(1026, sizes[2]); for (int i = 0; i < 3; i++) { var size = await client.GetMessageSizeAsync(i); Assert.AreEqual(sizes[i], size); } try { var message = await client.GetMessageAsync(0); using (var jpeg = new MemoryStream()) { var attachment = message.Attachments.OfType <MimePart> ().FirstOrDefault(); attachment.ContentObject.DecodeTo(jpeg); jpeg.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { var md5sum = HexEncode(md5.ComputeHash(jpeg)); Assert.AreEqual("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match."); } } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage: {0}", ex); } try { var messages = await client.GetMessagesAsync(0, 3); foreach (var message in messages) { using (var jpeg = new MemoryStream()) { var attachment = message.Attachments.OfType <MimePart> ().FirstOrDefault(); attachment.ContentObject.DecodeTo(jpeg); jpeg.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { var md5sum = HexEncode(md5.ComputeHash(jpeg)); Assert.AreEqual("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match."); } } } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessages: {0}", ex); } try { var messages = await client.GetMessagesAsync(new [] { 0, 1, 2 }); foreach (var message in messages) { using (var jpeg = new MemoryStream()) { var attachment = message.Attachments.OfType <MimePart> ().FirstOrDefault(); attachment.ContentObject.DecodeTo(jpeg); jpeg.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { var md5sum = HexEncode(md5.ComputeHash(jpeg)); Assert.AreEqual("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match."); } } } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessages: {0}", ex); } try { var header = await client.GetMessageHeadersAsync(0); Assert.AreEqual("Test inline image", header[HeaderId.Subject]); } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageHeaders: {0}", ex); } try { var headers = await client.GetMessageHeadersAsync(0, 3); Assert.AreEqual(3, headers.Count); for (int i = 0; i < headers.Count; i++) { Assert.AreEqual("Test inline image", headers[i][HeaderId.Subject]); } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageHeaders: {0}", ex); } try { var headers = await client.GetMessageHeadersAsync(new [] { 0, 1, 2 }); Assert.AreEqual(3, headers.Count); for (int i = 0; i < headers.Count; i++) { Assert.AreEqual("Test inline image", headers[i][HeaderId.Subject]); } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageHeaders: {0}", ex); } try { using (var stream = await client.GetStreamAsync(0)) { } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetStream: {0}", ex); } try { var streams = await client.GetStreamsAsync(0, 3); Assert.AreEqual(3, streams.Count); for (int i = 0; i < 3; i++) { streams[i].Dispose(); } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetStreams: {0}", ex); } try { var streams = await client.GetStreamsAsync(new int[] { 0, 1, 2 }); Assert.AreEqual(3, streams.Count); for (int i = 0; i < 3; i++) { streams[i].Dispose(); } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetStreams: {0}", ex); } try { await client.NoOpAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in NoOp: {0}", ex); } try { await client.DeleteMessageAsync(0); } catch (Exception ex) { Assert.Fail("Did not expect an exception in DeleteMessage: {0}", ex); } try { await client.ResetAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Reset: {0}", ex); } try { await client.DeleteMessagesAsync(new [] { 0, 1, 2 }); } catch (Exception ex) { Assert.Fail("Did not expect an exception in DeleteMessages: {0}", ex); } try { await client.ResetAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Reset: {0}", ex); } try { await client.DeleteMessagesAsync(0, 3); } catch (Exception ex) { Assert.Fail("Did not expect an exception in DeleteMessages: {0}", ex); } try { await client.ResetAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Reset: {0}", ex); } try { await client.DeleteAllMessagesAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in DeleteAllMessages: {0}", ex); } try { await client.ResetAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Reset: {0}", ex); } try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public static void Run() { // Connect and log in to POP3 const string host = "host"; const int port = 110; const string username = "******"; const string password = "******"; Pop3Client client = new Pop3Client(host, port, username, password); try { // ExStart:GetEmailsWithTodayDate // Emails that arrived today MailQueryBuilder builder = new MailQueryBuilder(); builder.InternalDate.On(DateTime.Now); // ExEnd:GetEmailsWithTodayDate // Build the query and Get list of messages MailQuery query = builder.GetQuery(); Pop3MessageInfoCollection messages = client.ListMessages(query); Console.WriteLine("Pop3: " + messages.Count + " message(s) found."); builder = new MailQueryBuilder(); // ExStart:GetEmailsOverDateRange // Emails that arrived in last 7 days builder.InternalDate.Before(DateTime.Now); builder.InternalDate.Since(DateTime.Now.AddDays(-7)); // ExEnd:GetEmailsOverDateRange // Build the query and Get list of messages query = builder.GetQuery(); messages = client.ListMessages(query); Console.WriteLine("Pop3: " + messages.Count + " message(s) found."); builder = new MailQueryBuilder(); // ExStart:GetSpecificSenderEmails // Get emails from specific sender builder.From.Contains("[email protected]"); // ExEnd:GetSpecificSenderEmails // Build the query and Get list of messages query = builder.GetQuery(); messages = client.ListMessages(query); Console.WriteLine("Pop3: " + messages.Count + " message(s) found."); builder = new MailQueryBuilder(); // ExStart:GetSpecificDomainEmails // Get emails from specific domain builder.From.Contains("SpecificHost.com"); // ExEnd:GetSpecificDomainEmails // Build the query and Get list of messages query = builder.GetQuery(); messages = client.ListMessages(query); Console.WriteLine("Pop3: " + messages.Count + " message(s) found."); builder = new MailQueryBuilder(); // ExStart:GetSpecificRecipientEmails // Get emails sent to specific recipient builder.To.Contains("recipient"); // ExEnd:GetSpecificRecipientEmails // Build the query and Get list of messages query = builder.GetQuery(); messages = client.ListMessages(query); Console.WriteLine("Pop3: " + messages.Count + " message(s) found."); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Example showing: /// - how to use UID's (unique ID's) of messages from the POP3 server /// - how to download messages not seen before /// (notice that the POP3 protocol cannot see if a message has been read on the server /// before. Therefore the client need to maintain this state for itself) /// </summary> /// <param name="hostname">Hostname of the server. For example: pop3.live.com</param> /// <param name="port">Host port to connect to. Normally: 110 for plain POP3, 995 for SSL POP3</param> /// <param name="useSsl">Whether or not to use SSL to connect to server</param> /// <param name="username">Username of the user on the server</param> /// <param name="password">Password of the user on the server</param> /// <param name="seenUids"> /// List of UID's of all messages seen before. /// New message UID's will be added to the list. /// Consider using a HashSet if you are using >= 3.5 .NET /// </param> /// <returns>A List of new Messages on the server</returns> public static List <EmailMessage> FetchUnseenMessages(string hostname, int port, bool useSsl, string username, string password, List <string> seenUids) { // The client disconnects from the server when being disposed using (var client = new Pop3Client()) { // Connect to the server client.Connect(hostname, port, useSsl); // Authenticate ourselves towards the server client.Authenticate(username, password); // Fetch all the current uids seen var uids = client.GetMessageUids(); // Create a list we can return with all new messages var newMessages = new List <EmailMessage>(); // All the new messages not seen by the POP3 client for (var i = 0; i < uids.Count; i++) { var currentUidOnServer = uids[i]; if (!seenUids.Contains(currentUidOnServer)) { // We have not seen this message before. // Download it and add this new uid to seen uids // the uids list is in messageNumber order - meaning that the first // uid in the list has messageNumber of 1, and the second has // messageNumber 2. Therefore we can fetch the message using // i + 1 since messageNumber should be in range [1, messageCount] var unseenMessage = client.GetMessage(i + 1); // Add the message to the new messages newMessages.Add(new EmailMessage { message = unseenMessage, messageId = currentUidOnServer }); // Add the uid to the seen uids, as it has now been seen seenUids.Add(currentUidOnServer); } } // Return our new found messages return(newMessages); } }
/// <summary> /// Check the import mailbox. Returns the first CSV file in the mailbox. /// </summary> /// <returns></returns> public async Task CheckMailBoxForImport(PerformContext hangfireContext) { Pop3Client pop3Client = new Pop3Client(); await pop3Client.ConnectAsync(Configuration["SPD_IMPORT_POP3_SERVER"], Configuration["SPD_IMPORT_POP3_USERNAME"], Configuration["SPD_IMPORT_POP3_PASSWORD"], true); List <Pop3Message> messages = (await pop3Client.ListAndRetrieveAsync()).ToList(); foreach (Pop3Message message in messages) { var attachments = message.Attachments.ToList(); if (attachments.Count > 0) { // string payload = null; // File.ReadAllText("C:\\tmp\\testimport.csv"); string payload = Encoding.Default.GetString(attachments[0].GetData()); if (payload != null) // parse the payload { List <WorkerResponse> responses = WorkerResponseParser.ParseWorkerResponse(payload, _logger); foreach (WorkerResponse workerResponse in responses) { // search for the Personal History Record. MicrosoftDynamicsCRMadoxioPersonalhistorysummary record = _dynamics.Personalhistorysummaries.GetByWorkerJobNumber(workerResponse.RecordIdentifier); if (record != null) { // update the record. MicrosoftDynamicsCRMadoxioPersonalhistorysummary patchRecord = new MicrosoftDynamicsCRMadoxioPersonalhistorysummary() { AdoxioSecuritystatus = SPDResultTranslate.GetTranslatedSecurityStatus(workerResponse.Result), AdoxioCompletedon = workerResponse.DateProcessed }; try { _dynamics.Personalhistorysummaries.Update(record.AdoxioPersonalhistorysummaryid, patchRecord); } catch (HttpOperationException odee) { hangfireContext.WriteLine("Error updating worker personal history"); hangfireContext.WriteLine("Request:"); hangfireContext.WriteLine(odee.Request.Content); hangfireContext.WriteLine("Response:"); hangfireContext.WriteLine(odee.Response.Content); _logger.LogError("Error updating worker personal history"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } } } } } await pop3Client.DeleteAsync(message); hangfireContext.WriteLine("Deleted message:"); _logger.LogError("Deleted message:"); } }
public async void TestGMailPop3Client() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "gmail.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "gmail.capa1.txt")); commands.Add(new Pop3ReplayCommand("AUTH PLAIN\r\n", "gmail.plus.txt")); commands.Add(new Pop3ReplayCommand("AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "gmail.auth.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "gmail.capa2.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "gmail.stat.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "gmail.retr1.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "gmail.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(GMailCapa1, client.Capabilities); Assert.AreEqual(2, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH2"), "Expected SASL XOAUTH2 auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); // Note: remove the XOAUTH2 auth mechanism to force PLAIN auth client.AuthenticationMechanisms.Remove("XOAUTH2"); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(GMailCapa2, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(3, client.Count, "Expected 3 messages"); try { var message = await client.GetMessageAsync(0); using (var jpeg = new MemoryStream()) { var attachment = message.Attachments.OfType <MimePart> ().FirstOrDefault(); attachment.ContentObject.DecodeTo(jpeg); jpeg.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { var md5sum = HexEncode(md5.ComputeHash(jpeg)); Assert.AreEqual("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match."); } } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage: {0}", ex); } try { var messages = await client.GetMessagesAsync(new [] { 0, 1, 2 }); foreach (var message in messages) { using (var jpeg = new MemoryStream()) { var attachment = message.Attachments.OfType <MimePart> ().FirstOrDefault(); attachment.ContentObject.DecodeTo(jpeg); jpeg.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { var md5sum = HexEncode(md5.ComputeHash(jpeg)); Assert.AreEqual("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match."); } } } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessages: {0}", ex); } try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public async void TestExchangePop3Client() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "exchange.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "exchange.capa.txt")); commands.Add(new Pop3ReplayCommand("AUTH PLAIN\r\n", "exchange.plus.txt")); commands.Add(new Pop3ReplayCommand("AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "exchange.auth.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "exchange.capa.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "exchange.stat.txt")); commands.Add(new Pop3ReplayCommand("UIDL\r\n", "exchange.uidl.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "exchange.retr1.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "exchange.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(ExchangeCapa, client.Capabilities); Assert.AreEqual(3, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("GSSAPI"), "Expected SASL GSSAPI auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("NTLM"), "Expected SASL NTLM auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); // Note: remove these auth mechanisms to force PLAIN auth client.AuthenticationMechanisms.Remove("GSSAPI"); client.AuthenticationMechanisms.Remove("NTLM"); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(ExchangeCapa, client.Capabilities); Assert.AreEqual(3, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("GSSAPI"), "Expected SASL GSSAPI auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("NTLM"), "Expected SASL NTLM auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); Assert.AreEqual(7, client.Count, "Expected 7 messages"); try { var uids = await client.GetMessageUidsAsync(); Assert.AreEqual(7, uids.Count, "Expected 7 uids"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageUids: {0}", ex); } try { var message = await client.GetMessageAsync(0); // TODO: assert that the message is byte-identical to what we expect } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage: {0}", ex); } try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
/// <summary> /// Effettua la connessione al server di posta elettronica /// </summary> /// <param name="accountInfo">The information account</param> public Boolean Connect(MailUser accountInfo) { Boolean bRetVal = false; AccountInfo = accountInfo; ErrorMessage = ""; if (this._pop3Client == null || !this._pop3Client.IsConnected) { if (accountInfo != null) // && accountInfo.IncomingProtocol.Equals("POP3") ) { this._pop3Client = new Pop3Client(); this._pop3Client.Disconnected += new DisconnectedEventHandler(On_pop3ClientDisconnected); this._pop3Client.Connected += new ConnectedEventHandler(On_pop3ClientConnected); this._pop3Client.Authenticating += new AuthenticatingEventHandler(On_pop3Client_Authenticating); this._pop3Client.Authenticated += new AuthenticatedEventHandler(On_pop3Client_Authenticated); Init(KbLogEnabled); int port = accountInfo.PortIncomingServer; bool ssl = accountInfo.IsIncomeSecureConnection; string serverName = accountInfo.IncomingServer; string user = accountInfo.LoginId; string password = accountInfo.Password; bool useInPort = accountInfo.PortIncomingChecked; try { if (ssl) { if (useInPort) { this._pop3Client.ConnectSsl(serverName, port, user, password); } else { this._pop3Client.ConnectSsl(serverName, user, password); } } else { if (useInPort) { this._pop3Client.Connect(serverName, port, user, password); } else { this._pop3Client.Connect(serverName, user, password); } } bRetVal = true; } catch (Exception ex) { if (ex.GetType() != typeof(ManagedException)) { ManagedException mEx = new ManagedException( "Errore nel metodo 'Connect: '" + ex.Message, "POP3_ERR_001", string.Empty, "Casella mail: " + ((AccountInfo.LoginId != null) ? AccountInfo.LoginId : " vuoto. ") + "Server Name: " + ((serverName.ToString() != null) ? serverName.ToString() : " vuoto. "), //EnanchedInfo ex.InnerException); ErrorLogInfo err = new ErrorLogInfo(mEx); log.Error(err); } ErrorMessage = ex.Message; StatusConnected = false; bRetVal = false; } } } bRetVal = this._pop3Client.IsConnected; return(bRetVal); }
static void Main(string[] args) { Console.WriteLine("Subject:"); var subject = Console.ReadLine(); Console.WriteLine("Receiver EMAIL: "); var receiver = Console.ReadLine(); Console.WriteLine("Sender EMAIL:"); var sender = Console.ReadLine(); Console.WriteLine("Sender PASSWORD:"******"Type Message:"); var messagetext = Console.ReadLine(); var message = new MimeMessage(); message.From.Add(new MailboxAddress(sender)); message.To.Add(new MailboxAddress(receiver)); message.Subject = subject; var builder = new BodyBuilder(); builder.TextBody = messagetext; var image = builder.LinkedResources.Add(@"C:\Users\Daniela\Desktop\simba.png"); image.ContentId = MimeUtils.GenerateMessageId(); builder.HtmlBody = string.Format($"<p>{messagetext} </p><br> " + @"<center><img src=""cid:{0}""></center>", image.ContentId); builder.Attachments.Add(@"C:\Users\Daniela\Desktop\WordFile.docx"); message.Body = builder.ToMessageBody(); try { using (var client = new SmtpClient(new ProtocolLogger(Console.OpenStandardOutput()))) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.StartTls); client.Authenticate(sender, psender); client.Send(message); client.Disconnect(true); Console.WriteLine("Send Mail Success."); } Console.WriteLine("Nummber of message to receive:"); var maxCount = Convert.ToInt32(Console.ReadLine()); using (var clientreceive = new Pop3Client()) { clientreceive.Connect("pop.gmail.com", 995, true); clientreceive.Authenticate(sender, psender); var emails = new List <MimeMessage>(); for (var i = 0; i < clientreceive.Count && i < maxCount; i++) { emails.Add(clientreceive.GetMessage(i)); } emails.ForEach(x => Console.WriteLine($"From: {x.From.Mailboxes.First()}\n" + $"Subject: {x.Subject}\nContent: {x.TextBody}")); clientreceive.Disconnect(true); Console.WriteLine("Receive Mail Success."); } } catch (Exception e) { Console.WriteLine("Send Mail Failed : " + e.Message); } Console.ReadLine(); }
private async Task <List <MimeMessage> > RecieveEmails(IEmailConfiguration configuration) { List <MimeMessage> emails = new List <MimeMessage>(); try { EmailFolder = await _alfrescoHttp.GetNodeInfo(AlfrescoNames.Aliases.Root, ImmutableList <Parameter> .Empty .Add(new Parameter(AlfrescoNames.Headers.Include, AlfrescoNames.Includes.Properties, ParameterType.QueryString)) .Add(new Parameter(AlfrescoNames.Headers.RelativePath, "Sites/Mailroom/documentLibrary/MailBox/Unprocessed", ParameterType.QueryString))); NewTimestampText = GetTimestampProperty(EmailFolder); using (var emailClient = new Pop3Client()) { emailClient.Connect(configuration.Pop3.Host, configuration.Pop3.Port, configuration.Pop3.UseSSL); // Remove OAUTH2 because we dont use it right now. emailClient.AuthenticationMechanisms.Remove("XOAUTH2"); emailClient.Authenticate(configuration.Username, configuration.Password); for (int i = 0; i < emailClient.Count; i++) { using (var memory = new MemoryStream()) { var message = emailClient.GetMessage(i); // Check if message was downloaded if (IsMessageAlreadyDownloaded(configuration.Username, message)) { continue; } message.WriteTo(memory); // If third parameter is set - It will end up with badrequest var file = new FormDataParam(memory.ToArray(), $"{IdGenerator.GenerateId()}.eml", null, "message/rfc822"); var emlFile = await SaveEMLFile(message, file); if (emlFile == null) { return(emails); } var attachments = await SaveAllAttachments(message.Attachments, emlFile?.Entry?.Id); await _alfrescoHttp.UpdateNode(emlFile?.Entry?.Id, new NodeBodyUpdate() .AddProperty("ssl:digitalDeliveryAttachmentsCount", attachments?.Count)); if (attachments == null) { emailClient.Disconnect(false); return(emails); } if (emlFile == null) { // Delete all attachments if eml fails to upload await DeleteNodes(attachments); emailClient.Disconnect(false); return(emails); } try { // Update attachment count await _alfrescoHttp.UpdateNode(emlFile?.Entry?.Id, new NodeBodyUpdate() .AddProperty(ComponentCounterProperty, attachments.Count)); await CreateAllSecondaryChildren(emlFile, attachments); } catch { // Delete .eml file and it's attachments if ucreation of secondary childrens fails await DeleteNode(emlFile); await DeleteNodes(attachments); emailClient.Disconnect(false); return(emails); } EmailProvider provider = new EmailProvider(configuration); try { var body = GetAutomaticResponseBodyText( Path.Combine(_emailServerConfiguration.AutomaticResponse.BodyTextFile.Folder, _emailServerConfiguration.AutomaticResponse.BodyTextFile.FileName), new List <ReplaceTexts> { new ReplaceTexts("[predmet_doruceneho_emailu]", message.Subject), new ReplaceTexts("[nazev_organizace]", _emailServerConfiguration.AutomaticResponse.OrganizationName) }); await SendEmail( message?.From?.Mailboxes?.FirstOrDefault()?.Address, configuration.Username, _emailServerConfiguration?.AutomaticResponse?.EmailSubject, body); } catch (Exception e) { } // if succesfully is uploaded emails.Add(emailClient.GetMessage(i)); CurrentDownloadedMessagesCount++; await SaveTimeStamp(configuration.Username, message); } } // update download time anyway await SaveTimeStamp(configuration.Username); // Disconect marks emails as "downloaded" and they will not appear next time emailClient.Disconnect(true); return(emails); } } catch (Exception e) { Log.Error(e.Message); return(emails); } }
public async void TestBasicPop3Client() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "comcast.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "comcast.capa1.txt")); commands.Add(new Pop3ReplayCommand("USER username\r\n", "comcast.ok.txt")); commands.Add(new Pop3ReplayCommand("PASS password\r\n", "comcast.ok.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "comcast.capa2.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "comcast.stat1.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "comcast.retr1.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "comcast.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.IsFalse(client.IsSecure, "IsSecure should be false."); Assert.AreEqual(ComcastCapa1, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(31, client.ExpirePolicy, "ExpirePolicy"); Assert.AreEqual(100000, client.Timeout, "Timeout"); client.Timeout *= 2; try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(ComcastCapa2, client.Capabilities); Assert.AreEqual("ZimbraInc", client.Implementation); Assert.AreEqual(2, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("X-ZIMBRA"), "Expected SASL X-ZIMBRA auth mechanism"); Assert.AreEqual(-1, client.ExpirePolicy); Assert.AreEqual(1, client.Count, "Expected 1 message"); try { var message = await client.GetMessageAsync(0); // TODO: assert that the message is byte-identical to what we expect } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage: {0}", ex); } try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public static void Get_URL_Confirm(E_Mail mail) { int tentativas_get_code = 0; INICIO: string Confirm_Link = ""; string Pop3HostName = ""; var splittogetdomain = mail.EMAIL.Split('@'); string domainName = splittogetdomain[1]; var popconfig = Main.pop3s.Where(a => a.SuportedDomains.Contains(domainName)).FirstOrDefault(); if (popconfig != null) { Pop3HostName = popconfig.PoP3Server; } else { Log.error($"Pop3 HostName not defined for {domainName}"); return; } string username = mail.EMAIL, password = mail.PASS; using (var client = new Pop3Client()) { try { client.Connect(Pop3HostName, 995, true); client.Authenticate(username, password); if (client.IsAuthenticated == true) { Pop3Client = client; } } catch (Exception ex) { Log.error("Error to acess E-mail: " + username); Log.error(ex.Message); } while (Confirm_Link == "") { if (tentativas_get_code < 6) { try { var message1 = client.GetMessage(client.Count - 1); var creationid = new Regex("creationid=(\\d+)").Match(message1.HtmlBody.ToString()).Groups[1].Value; var stoken = new Regex("(?<=stoken\\=)\\w+").Match(message1.HtmlBody.ToString()).Value; bool ja_usado = CreationID_DB.Check_AlreadyUsed(creationid); if (ja_usado == true) { goto INICIO; } else { Confirm_Link = $"https://store.steampowered.com/account/newaccountverification?stoken={stoken}&creationid={creationid}"; var request = new RequestBuilder(Confirm_Link).GET().Execute(); Log.info($"Link Successfully Found..."); Main._Form1.Invoke(new Action(() => { //Main._Form1.btn_SaveAcc.Enabled = true; Main._Form1.btn_GenLoginPass.Enabled = true; })); Thread th = new Thread(() => Main.CheckExistingAccountOnEmail()); th.IsBackground = true; th.Start(); Thread th1 = new Thread(() => Main.GenLoginAndPassAutomatic()); th1.IsBackground = true; th1.Start(); lock (locker) { CreationID_DB.ADD_TO_DB(creationid); } } } catch { Log.error("Erro To get Confirm URL. Try Again!!"); Thread.Sleep(TimeSpan.FromSeconds(15)); tentativas_get_code = tentativas_get_code + 1; client.Disconnect(true); goto INICIO; } } else { Log.error("Erro To get Confirm URL From Email!"); } } client.Disconnect(true); } }
private void Read_Emails() { Pop3Client pop3Client; if (Session["Pop3Client"] == null) { pop3Client = new Pop3Client(); pop3Client.Connect("pop.gmail.com", 995, true); pop3Client.Authenticate("recent:[email protected]", "umakantmore", AuthenticationMethod.UsernameAndPassword); //pop3Client.Authenticate("*****@*****.**", "umakantmore@08", AuthenticationMethod.UsernameAndPassword); Session["Pop3Client"] = pop3Client; } else { pop3Client = (Pop3Client)Session["Pop3Client"]; } int count = pop3Client.GetMessageCount(); this.Emails = new List <Email>(); int counter = 0; for (int i = count; i >= 1; i--) { Message message = pop3Client.GetMessage(i); Email email = new Email() { MessageNumber = i, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address), }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstPlainTextVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.Attachments.Add(new Attachment { FileName = attachment.FileName, ContentType = attachment.ContentType.MediaType, Content = attachment.Body }); } this.Emails.Add(email); counter++; if (counter > 8) { break; } } repCategory.DataSource = this.Emails; repCategory.DataBind(); }
private void fetchAllMessages(object sender, DoWorkEventArgs e) { int percentComplete; // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server //client.Connect("pop.gmail.com", 995, true); //Taking the data from usersettings.settings client.Connect(MailClient__.Properties.Settings.Default.openpopserver, MailClient__.Properties.Settings.Default.popport, MailClient__.Properties.Settings.Default.EnableSSL); // Authenticate ourselves towards the server client.Authenticate(username, password); // Get the number of messages in the inbox messageCount = client.GetMessageCount(); // We want to download all messages List <OpenPop.Mime.Message> allMessages = new List <OpenPop.Mime.Message>(messageCount); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); percentComplete = Convert.ToInt16((Convert.ToDouble(allMessages.Count) / Convert.ToDouble(messageCount)) * 100); (sender as BackgroundWorker).ReportProgress(percentComplete); } // Now return the fetched messages e.Result = allMessages; SQLiteCommand commandInsert = new SQLiteCommand("INSERT OR IGNORE INTO messages (id, sender, subject, body) VALUES (@id, @sender, @subject, @body)", connection); connection.Open(); foreach (OpenPop.Mime.Message message in allMessages) { if (message.Headers.MessageId != null) { commandInsert.Parameters.AddWithValue("@id", message.Headers.MessageId); commandInsert.Parameters.AddWithValue("@sender", message.Headers.From.Address); commandInsert.Parameters.AddWithValue("@subject", message.Headers.Subject); if (!message.MessagePart.IsMultiPart) { commandInsert.Parameters.AddWithValue("@body", message.MessagePart.GetBodyAsText()); } else { OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion(); commandInsert.Parameters.AddWithValue("@body", plainText.GetBodyAsText()); } int result = commandInsert.ExecuteNonQuery(); } } commandInsert.Dispose(); connection.Close(); } }
public async void TestInvalidStateExceptions() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "comcast.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "comcast.capa1.txt")); commands.Add(new Pop3ReplayCommand("USER username\r\n", "comcast.ok.txt")); commands.Add(new Pop3ReplayCommand("PASS password\r\n", "comcast.err.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "comcast.quit.txt")); using (var client = new Pop3Client()) { Assert.Throws <ServiceNotConnectedException> (async() => await client.AuthenticateAsync("username", "password")); Assert.Throws <ServiceNotConnectedException> (async() => await client.AuthenticateAsync(new NetworkCredential("username", "password"))); Assert.Throws <ServiceNotConnectedException> (async() => await client.NoOpAsync()); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageSizesAsync()); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageSizeAsync("uid")); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageSizeAsync(0)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageUidsAsync()); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageUidAsync(0)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageAsync("uid")); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageAsync(0)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageHeadersAsync("uid")); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageHeadersAsync(0)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetStreamAsync(0)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetStreamsAsync(0, 1)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetStreamsAsync(new int[] { 0 })); Assert.Throws <ServiceNotConnectedException> (async() => await client.DeleteMessageAsync("uid")); Assert.Throws <ServiceNotConnectedException> (async() => await client.DeleteMessageAsync(0)); try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(ComcastCapa1, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(31, client.ExpirePolicy); Assert.Throws <AuthenticationException> (async() => await client.AuthenticateAsync("username", "password")); Assert.IsTrue(client.IsConnected, "AuthenticationException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageSizesAsync()); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageSizeAsync("uid")); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageSizeAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageUidsAsync()); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageUidAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageAsync("uid")); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageHeadersAsync("uid")); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageHeadersAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetStreamAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetStreamsAsync(0, 1)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetStreamsAsync(new int[] { 0 })); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.DeleteMessageAsync("uid")); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.DeleteMessageAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public void Init() { Client = new Pop3Client(); }
public static List <Message> DownloadAllMail() { SetMailprovider(login); updt = DateTime.Now; Console.WriteLine("{0:HH:mm:ss tt}", updt); bool loginsuccess = true; Pop3Client client = new Pop3Client(); client.Connect(hostname, port, usessl); Console.Write("login: "******"\nPassword: "******"Wrong login/password"); loginsuccess = false; } if (loginsuccess) { int totalamount = client.GetMessageCount(); Console.WriteLine("Number of emails: " + totalamount); Console.WriteLine("Please wait..."); List <Message> allMail = new List <Message>(); for (int i = totalamount; i > 0; i--) { try { allMail.Add(client.GetMessage(i)); } catch (Exception e) { // Console.WriteLine(i + " ==--== " + e.Message); client.Dispose(); client = new Pop3Client(); client.Connect("pop.gmail.com", 995, true); client.Authenticate(login, pass, AuthenticationMethod.UsernameAndPassword); i++; } } Console.SetCursorPosition(0, Console.CursorTop - 1); Console.WriteLine("Emails dowloaded: " + allMail.Count()); // Message msgtest = client.GetMessage(totalamount); // Console.WriteLine(msgtest.Headers.From + " " + msgtest.Headers.Subject); // Console.WriteLine(msgtest.ToMailMessage().Body); // msgtest = client.GetMessage(1); // Console.WriteLine(msgtest.Headers.From + " " + msgtest.Headers.Subject); // ////Console.WriteLine(msgtest.ToMailMessage().Body); // //msgtest = client.GetMessage(totalamount-2); // //Console.WriteLine(msgtest.Headers.From + " " + msgtest.Headers.Subject); // //try { // // // Console.WriteLine(msgtest.ToMailMessage().IsBodyHtml); // //} // //catch(Exception ex) // //{ // // Console.WriteLine(ex.Message); // //} // //msgtest = client.GetMessage(totalamount-3); // //Console.WriteLine(msgtest.Headers.From + " " + msgtest.Headers.Subject); // //Console.WriteLine(msgtest.ToMailMessage().Body); //client.Disconnect(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); return(allMail); } else { return(null); } }
private static MailMessage[] GetMailMessagesByPOP3(string contentListPath) { var messages = new List <MailMessage>(); var credentials = MailProvider.Instance.GetPOP3Credentials(contentListPath); var pop3s = Settings.GetValue <POP3Settings>(MAILPROCESSOR_SETTINGS, SETTINGS_POP3, contentListPath) ?? new POP3Settings(); using (var client = new Pop3Client()) { try { client.Connect(pop3s.Server, pop3s.Port, pop3s.SSL); client.Authenticate(credentials.Username, credentials.Password); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error: connecting to mail server " + pop3s.Server + " with the username " + credentials.Username + " failed.", ex)); return(messages.ToArray()); } int messageCount; try { messageCount = client.GetMessageCount(); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error: getting messages failed. Content list: " + contentListPath, ex)); return(messages.ToArray()); } // Messages are numbered in the interval: [1, messageCount] // Most servers give the latest message the highest number for (var i = messageCount; i > 0; i--) { try { var msg = client.GetMessage(i); var mailMessage = msg.ToMailMessage(); //maybe we should skip messages without a real sender //if (mailMessage.Sender != null) messages.Add(mailMessage); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error. Content list: " + contentListPath, ex)); } } try { client.DeleteAllMessages(); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error: deleting messages failed. Content list: " + contentListPath, ex)); } } Logger.WriteVerbose("MailPoller workflow: " + messages.Count + " messages received. Content list: " + contentListPath); return(messages.ToArray()); }
public void DownloadEmail() { using (var client = new Pop3Client()) { Console.WriteLine("Conectando e-mail: " + _username); client.Connect(_hostname, _port, _useSsl); client.Authenticate(_username, _password, AuthenticationMethod.UsernameAndPassword); _emails.Clear(); if (client.Connected) { int messageCount = client.GetMessageCount(); var Messages = new List <Emails>(messageCount); for (int i = messageCount; i > 0; i--) { var popEmail = client.GetMessage(i); var popText = popEmail.FindFirstPlainTextVersion(); var popHtml = popEmail.FindFirstHtmlVersion(); string mailText = string.Empty; string mailHtml = string.Empty; if (popText != null) { mailText = popText.GetBodyAsText(); } if (popHtml != null) { mailHtml = popHtml.GetBodyAsText(); } Mensagem mensagem = new Mensagem() { Id = popEmail.Headers.MessageId, Assunto = popEmail.Headers.Subject, De = popEmail.Headers.From.Address, Para = string.Join("; ", popEmail.Headers.To.Select(to => to.Address)), Data = popEmail.Headers.DateSent, ConteudoTexto = mailText, anexos = popEmail.FindAllAttachments(), ConteudoHtml = !string.IsNullOrWhiteSpace(mailHtml) ? mailHtml : mailText }; _emails.Add(mensagem); Console.WriteLine("De: " + mensagem.De); Console.WriteLine("Data: " + mensagem.Data); foreach (var ado in mensagem.anexos) { ado.Save(new FileInfo(Path.Combine(_pathAnexo, ado.FileName))); Console.WriteLine("Exportado anexo: " + ado.FileName); } } } else { Console.WriteLine("Não consegui conectar"); } Console.ReadKey(); } }
//protected void RGVSMSSent_SortCommand(object sender, GridSortCommandEventArgs e) //{ // this.RGVSMSSent.MasterTableView.AllowNaturalSort = true; // this.RGVSMSSent.MasterTableView.Rebind(); //} //protected void RGVSMSSent_NeedDataSource(object sender, GridNeedDataSourceEventArgs e) //{ // GlobalGridBind(); //} //private void StudentSent_SMS() //{ // DataTable dtStudentLeadSMSSent = new DataTable(); // dtStudentLeadSMSSent = DataAccessManager.GetSMSSentStd(Convert.ToString(Session["StudentNo"]), Convert.ToString(Session["DeptID"]), Convert.ToInt32(Session["CampusID"])); // Session["dtStudentLeadSMSSent"] = dtStudentLeadSMSSent; // RGVSMSSent.DataSource = (DataTable)Session["dtStudentLeadSMSSent"]; //} //private void LeadSent_SMS() //{ // DataTable dtStudentLeadSMSSent = new DataTable(); // dtStudentLeadSMSSent = DataAccessManager.GetSMSSentLead(Convert.ToString(Session["LeadId"]), Convert.ToString(Session["DeptID"]), Convert.ToInt32(Session["CampusID"])); // Session["dtStudentLeadSMSSent"] = dtStudentLeadSMSSent; // RGVSMSSent.DataSource = (DataTable)Session["dtStudentLeadSMSSent"]; //} //protected void RGVSMSSent_PageIndexChanged(object sender, GridPageChangedEventArgs e) //{ // try // { // RGVSMSSent.DataSource = (DataTable)Session["dtStudentLeadSMSSent"]; // } // catch (Exception ex) // { // } //} #endregion public void fetchmail(string DeptID, int CampusID) { try { DataTable dtEmailConfig = DataAccessManager.GetEmailConfigDetail(DeptID, CampusID); if (dtEmailConfig.Rows.Count > 0) { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(dtEmailConfig.Rows[0]["Pop3"].ToString(), Convert.ToInt32(dtEmailConfig.Rows[0]["PortIn"]), Convert.ToBoolean(dtEmailConfig.Rows[0]["SSL"])); pop3Client.Authenticate(dtEmailConfig.Rows[0]["DeptEmail"].ToString(), dtEmailConfig.Rows[0]["Pass"].ToString(), AuthenticationMethod.UsernameAndPassword); if (pop3Client.Connected) { int count = pop3Client.GetMessageCount(); int progressstepno; if (count == 0) { } else { progressstepno = 100 - count; this.Emails = new List <Email>(); for (int i = 1; i <= count; i++) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); Email email = new Email() { MessageNumber = i, messageId = message.Headers.MessageId, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = message.Headers.From.Address }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } email.IsAttached = false; this.Emails.Add(email); //Attachment Process List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.IsAttached = true; string FolderName = string.Empty; FolderName = Convert.ToString(Session["CampusName"]); String path = Server.MapPath("~/InboxAttachment/" + FolderName); if (!Directory.Exists(path)) { // Try to create the directory. DirectoryInfo di = Directory.CreateDirectory(path); } string ext = attachment.FileName.Split('.')[1]; // FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\") + attachment.FileName.ToString()); FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\" + FolderName + "\\") + attachment.FileName.ToString()); attachment.SaveToFile(file); Attachment att = new Attachment(); att.messageId = message.Headers.MessageId; att.FileName = attachment.FileName; attItem.Add(att); } //System.Threading.Thread.Sleep(500); } //Insert into database Inbox table DataTable dtStudentNo = new DataTable(); bool IsReadAndSave = false; foreach (var ReadItem in Emails) { string from = string.Empty, subj = string.Empty, messId = string.Empty, Ebody = string.Empty; from = Convert.ToString(ReadItem.From); subj = Convert.ToString(ReadItem.Subject); messId = Convert.ToString(ReadItem.messageId); Ebody = Convert.ToString(ReadItem.Body); if (Ebody != string.Empty && Ebody != null) { Ebody = Ebody.Replace("'", " "); } DateTime date = ReadItem.DateSent; bool IsAtta = ReadItem.IsAttached; //Student Email if (Source.SOrL(Convert.ToString(Session["StudentNo"]), Convert.ToString(Session["leadID"]))) { dtStudentNo = DyDataAccessManager.GetStudentNo(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase(dtStudentNo.Rows[0]["StudentNo"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } //Leads Email if (Source.SOrL(Convert.ToString(Session["ParamStudentNo"]), Convert.ToString(Session["ParamleadID"])) == false) { dtStudentNo = DyDataAccessManager.GetLeadsID(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead(dtStudentNo.Rows[0]["LeadsID"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } // } //Insert into database Attachment table foreach (var attachItem in attItem) { bool success; string Filname = attachItem.FileName; string MssID = attachItem.messageId; success = DataAccessManager.ReadEmailAttachmentAndSaveDatabase(MssID, Filname); } Emails.Clear(); // attItem.Clear(); pop3Client.DeleteAllMessages(); //StartNotification(count); } } pop3Client.Disconnect(); } } catch (Exception ex) { } }
protected override void Execute(NativeActivityContext context) { string username = Email.Get(context); //发送端账号 string password = Password.Get(context); //发送端密码(这个客户端重置后的密码) string server = Server.Get(context); //邮件服务器 Int32 port = Port.Get(context); //端口号 Int32 counts = Counts.Get(context); List <object> configList = new List <object>(); Pop3Client emailClient = new Pop3Client(); List <MimeMessage> emails = new List <MimeMessage>(); string mailTopicKey = MailTopicKey.Get(context); string mailSenderKey = MailSenderKey.Get(context); string mailTextBodyKey = MailTextBodyKey.Get(context); try { emailClient.Connect(server, port, SecureConnection); emailClient.Authenticate(username, password); for (int i = emailClient.Count - 1, j = 0; i >= 0 && j < counts; i--, j++) { MimeMessage message = emailClient.GetMessage(i); InternetAddressList Sender = message.From; string SenderStr = Sender[0].Name; string Topic = message.Subject; if (mailTopicKey != null && mailTopicKey != "") { if (Topic == null || Topic == "") { j--; continue; } if (!Topic.Contains(mailTopicKey)) { j--; continue; } } if (mailSenderKey != null && mailSenderKey != "") { if (SenderStr == null || SenderStr == "") { j--; continue; } if (!SenderStr.Contains(mailSenderKey)) { j--; continue; } } if (mailTextBodyKey != null && mailTextBodyKey != "") { if (message.TextBody == null || message.TextBody == "") { j--; continue; } if (!message.TextBody.Contains(mailTextBodyKey)) { j--; continue; } } emails.Add(message); if (DeleteMessages) { emailClient.DeleteMessage(i); } } MailMsgList.Set(context, emails); emailClient.Disconnect(true); } catch (Exception e) { SharedObject.Instance.Output(SharedObject.enOutputType.Error, "获取POP3邮件失败", e.Message); emailClient.Disconnect(true); } configList.Add(server); configList.Add(port); configList.Add(SecureConnection); configList.Add(username); configList.Add(password); configList.Add(""); if (Body != null) { object[] buff = configList.ToArray(); context.ScheduleAction(Body, emails, emailClient, buff); } }