How can I delete a message by message id with MailKit POP3 client? - email

I want to use the MailKit Pop3Client to retrieve messages from a POP3 mailbox, and then delete these messages after processing. The retrieval code is something like:
Public Function GetMessages(Optional logPath As String = Nothing) As List(Of MimeMessage)
Dim client As Pop3Client
Dim messages = New List(Of MimeMessage)()
Using client
ConnectPop3(client)
Dim count = client.GetMessageCount()
For i As Integer = 0 To count - 1
Dim msg = client.GetMessage(i)
messages.Add(msg)
Next
End Using
Return messages
End Function
My problem here is in order to delete a message in another message, I need an index, but that is long gone once I exit GetMessages. All I have is the info available on a MimeMessage object, but that has no index property, only MessageId, but in my Delete method, I would have to read all mails again, in order to look up an index value.
Now Pop3Client has a GetMessageUid(int index) method, which returns a mysterious string (looks like int) value with no apparent relation at all to the Mime MessageID, but it seems this is all I have. Then I have to store the MailKit Uid with each message, making my retrieval code something like this, using a dictionary to store uid-message pairs:
Public Function GetMessages(Optional delete As Boolean = False, Optional logPath As String = Nothing) As List(Of MimeMessage)
Dim client As Pop3Client
Dim messages = New Dictionary(Of String, MimeMessage)
Using client
ConnectPop3(client)
Dim count = client.GetMessageCount()
For i As Integer = 0 To count - 1
Dim msg = client.GetMessage(i)
Dim u = client.GetMessageUid(i)
messages.Add(u, msg)
Next
client.Disconnect(True)
End Using
Return messages
End Function
I am really hoping I'm missing something here and what should be a really simple process is indeed simple, but I can't find anything else on my own.

The message UID is the only way to track a message between connections.
The index for a message can change as other messages are deleted.
Your options are:
Delete messages as you're downloading them.
Save the UID so you can come back and delete specific messages later.
It may make more sense if you skim through the POP3 RFC.

Related

How to get all Kubernetes Deployment objects using kubernetes java client?

I am planning to write simple program using kubernetes java client (https://github.com/kubernetes-client/java/). I could get all namespaces and pods but how do i get list of deployments in a given namespace? I couldn't find any method. Is there any way to get it?
for (V1Namespace ns: namespaces.getItems()) {
System.out.println("------Begin-----");
System.out.println("Namespace: " + ns.getMetadata().getName());
V1PodList pods = api.listNamespacedPod(ns.getMetadata().getName(), null, null, null, null, null, null, null, null, null);
int count = 0;
for (V1Pod pod: pods.getItems()) {
System.out.println("Pod " + (++count) + ": " + pod.getMetadata().getName());
System.out.println("Node: " + pod.getSpec().getNodeName());
}
System.out.println("------ENd-----");
}
I guess you're looking for the following example:
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://localhost");
// Configure API key authorization: BearerToken
ApiKeyAuth BearerToken = (ApiKeyAuth) defaultClient.getAuthentication("BearerToken");
BearerToken.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//BearerToken.setApiKeyPrefix("Token");
AppsV1Api apiInstance = new AppsV1Api(defaultClient);
String namespace = "namespace_example"; // String | object name and auth scope, such as for teams and projects
String pretty = "pretty_example"; // String | If 'true', then the output is pretty printed.
Boolean allowWatchBookmarks = true; // Boolean | allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored.
String _continue = "_continue_example"; // String | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
String fieldSelector = "fieldSelector_example"; // String | A selector to restrict the list of returned objects by their fields. Defaults to everything.
String labelSelector = "labelSelector_example"; // String | A selector to restrict the list of returned objects by their labels. Defaults to everything.
Integer limit = 56; // Integer | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
String resourceVersion = "resourceVersion_example"; // String | When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
Integer timeoutSeconds = 56; // Integer | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
Boolean watch = true; // Boolean | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
try {
V1DeploymentList result = apiInstance.listNamespacedDeployment(namespace, pretty, allowWatchBookmarks, _continue, fieldSelector, labelSelector, limit, resourceVersion, timeoutSeconds, watch);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AppsV1Api#listNamespacedDeployment");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}

Real Time signalR in ASP.NET error in .ContainsKey

I tried to chat with SignalR ised and ASP.Net (VB)
When running, works perfectly with the first user, but the login with another user get an error:
Error: Overflow
Please help, I'm new with realtime applications
Public Overrides Function OnConnected() As Task
Dim myRoomId = "XXXX"
Dim myUserId = IdentityUser.UserCode
SyncLock connections
If Not connections.ContainsKey(myRoomId) Then
connections(myRoomId) = New Dictionary(Of Integer, List(Of String))()
End If
If Not connections(myRoomId).ContainsKey(myUserId) Then ' <<<<<--- Error
connections(myRoomId)(myUserId) = New List(Of String)()
End If
connections(myRoomId)(myUserId).Add(Me.Context.ConnectionId)
End SyncLock
Return MyBase.OnConnected()
End Function
you're locking the object "connections" and trying to change it inside SyncLock which is not allowed.
Use an empty object to lock in SyncLock, it should be public and shared.
Also , you should not use "OnConnect()" event becuase it will fire everytime on hub method call
like this
Private Shared _lock_connections As New Object
Public Overrides Function OnConnected() As Task
Dim myRoomId = "XXXX"
Dim myUserId = IdentityUser.UserCode
SyncLock _lock_connections
If Not connections.ContainsKey(myRoomId) Then
connections(myRoomId) = New Dictionary(Of Integer, List(Of String))()
End If
If Not connections(myRoomId).ContainsKey(myUserId) Then ' <<<<<--- Error
connections(myRoomId)(myUserId) = New List(Of String)()
End If
connections(myRoomId)(myUserId).Add(Me.Context.ConnectionId)
End SyncLock
Return MyBase.OnConnected()
End Function

Cannot see if my queue is a transaction

I'm trying to send a message to a remote queue.
// Send a message to the queue.
if (myQueue.Transactional)
{
var myTransaction = new MessageQueueTransaction();
myTransaction.Begin();
Message objMessage = new Message();
objMessage.UseDeadLetterQueue = true;
objMessage.Body = message;
myQueue.Send(objMessage, myTransaction);
myTransaction.Commit();
}
else
{
Message objMessage = new Message();
objMessage.UseDeadLetterQueue = true;
objMessage.Body = message;
myQueue.Send(message);
}
but I get an exception
The specified format name does not support the requested operation. For example, a direct queue format name cannot be deleted.
I assume that my queue name is incorrect or I have a permission error so I enabled the dead letter queue but it's empty. My queue name is "FormatName:Direct=TCP:xx.xxx.xx.xx\private$\Test"
Thanks
You can't query information about a remote private queue.
Local queues, yes. Remote public queues, yes, but not with Formatname.

Email Fails to send with sms details

The following code listens for an incoming sms, takes all the spaces out of the sms then emails the edited sms. Everything works fine, except that the app fails to send an email. Can anyone see what I am doing wrong and help me?
new Thread() {
public void run() {
try {
DatagramConnection _dc =
(DatagramConnection)Connector.open("sms://");
for(;;) { //'For-Loop' used to listen continously for incoming sms's
Datagram d = _dc.newDatagram(_dc.getMaximumLength());
_dc.receive(d); //The sms is received
byte[] bytes = d.getData();
String address = d.getAddress(); //The address of the sms is put on a string.
String msg = new String(bytes); //The body of the sms is put on a string.
String msg2 = (replaceAll(msg, " ","")) ; //
Store store = Session.getDefaultInstance().getStore();
Folder[] folders = store.list(Folder.SENT);
Folder sentfolder = folders[0]; //Retrieve the sent folder
Message in = new Message(sentfolder);
Address recipients[] = new Address[1];
recipients[0]= new Address("me#yahoo.com", "user");
in.addRecipients(Message.RecipientType.TO, recipients);
in.setSubject("Incoming SMS"); //The subject of the message is added
in.setContent("You have just received an SMS from: " + address + "/n" + "Message: " + msg2); //Here the body of the message is formed
in.setPriority(Message.Priority.HIGH); //The priority of the message is set.
Transport.send(in); //The message is sent
in.setFlag(Message.Flag.OPENED, true);
Folder folder = in.getFolder(); //The message is deleted from the sent folder
folder.deleteMessage(in);
}
}catch (Exception me) { //All Exceptions are caught
}
}
};
public static String replaceAll(String front, String pattern, String back) {
if (front == null)
return "";
StringBuffer sb = new StringBuffer(); //A StringBufffer is created
int idx = -1;
int patIdx = 0;
while ((idx = front.indexOf(pattern, patIdx)) != -1) {
sb.append(front.substring(patIdx, idx));
sb.append(back);
patIdx = idx + pattern.length();
}
sb.append(front.substring(patIdx));
return sb.toString();
}
Thanks
This isn't really an answer to the problem, just an elaboration on my comment above, that might help.
Make sure do something in your exception catch block, so that problems in the code don't go unnoticed. It's possible that your code is not encountering any exceptions, but in order for us to help, we need to try to eliminate potential problems, and since you say the code isn't working, but you have an empty exception handler, that's an easy area to fix first.
the simplest handler is just:
try {
// try sending sms here
} catch (Exception e) {
e.printStackTrace();
}
If you can run this in the debugger (which I highly suggest), then you can now put a breakpoint on the e.printStackTrace() line, and see if it ever gets hit. If it does, inspect the value of e and tell us what it is.
Normally, in my programs, I don't actually use e.printStackTrace() in catch handlers, but I have a logging class that takes strings, and maybe a log level (e.g. info, warning, error, verbose), and writes to a log file. The log file can be attached to emails the users send to tech support, or can be disabled for production if you only want to use the feature while developing.
Anyway, start with a simple printStackTrace() and see if it ever gets hit. Then, report back.
Edit: from the symptoms you describe in the comments after your question, it seems like it's a possibility that
String msg2 = (replaceAll(msg, " ","")) ; //
is throwing an exception, and therefore never letting you get to where you'd send the email. I can't see anything wrong with your implementation of replaceAll() upon initial inspection, but that might be a place to look. Has that implementation been thoroughly unit-tested?
Also, I think you have a "/n" in your code where you probably want a "\n", right?

How to intercept mail messages on a POP3 server

I need an application that will intercept all incoming mail messages and modify them according to some specs.
I am an absolute rookie at this, please detail :)
Try this sample code
Dim _tcpClient As New TcpClient
Dim _networkStream As NetworkStream
Dim _Msg As String
With _tcpClient
.Connect(Me.txtServerIp.Text, Integer.Parse(Me.txtPortNum.Text))
_networkStream = .GetStream
Dim sw As New StreamWriter(_networkStream)
Dim sr As New StreamReader(_networkStream)
If Not CheckError(sr.ReadLine()) Then
sw.WriteLine(String.Format("USER {0}", Me.txtUsername.Text))
sw.Flush()
End If
If Not CheckError(sr.ReadLine()) Then
sw.WriteLine(String.Format("PASS {0}", Me.txtPassword.Text))
sw.Flush()
End If
If Not CheckError(sr.ReadLine()) Then
sw.WriteLine("STAT ")
sw.Flush()
End If
_Msg = sr.ReadLine
Dim MsgCount As String = _Msg.Split(New String() {" "}, _
StringSplitOptions.RemoveEmptyEntries)(1)
If Integer.Parse(Me.lblMsgCount.Text) < Integer.Parse(MsgCount) Then
Me.lblMsgCount.Text = MsgCount
End If
sw.WriteLine("Quit ")
sw.Flush()
sw.Close()
sr.Close()
_networkStream.Close()
_tcpClient.Close()
End With
All incoming messages will be coming on over SMTP.
So, you need to do 1 of 2 things:
If your current server supports it, hook into it's SMTP events, and modify the message before it is passed on to the local intended user.
or
You will need a SMTP proxy service, that sits in front of your real SMTP server.
Inside of the SMTP proxy, modify the message, and pass it on to your real SMTP server.