Redemption: RDOMail accessing attachments and moving mail - plugins

I am trying to access the attachments for an RDOMail object. When I either search for a specific item using LINQ or just try and iterate through the list with a foreach it freezes outlook and throws no exception.
Also when I try and move the RDOMail to another folder it freezes outlook and throws no exception.
I can accomplish both these things just using the Outlook.MailItem
Anyone have any ideas?
void store_OnNewMail(string entryId)
{
RDOMail mail = _store.GetMessageFromID(entryId);
RDOAttachment protocolAttachment = mail.Attachments.Cast<RDOAttachment>().SingleOrDefault(attach => attach.FileName == "protocol.id");
mail.Move(_hiddenDeliveryTrustFolder);
}

My guess is that the IMAP4 message available at the time of the NewMail event is just an envelope message (header only, no body or attachments). When you access the attachments, IMAP4 provider attempts to connect to the IMAP4 server to retrieve the data, but the call is blocked because of a critical section signaled before the event is raised.
Try to bypass the IMAP4 provider level by
RDOStore unwrappedStore = rSession.Stores.UnwarpStore(_store);
RDOMail mail = unwrappedStore.GetMessageFromID(entryId);
You can also try to save the message entry id in a variable and start a timer (use the one from the Forms namespace). When the timer event fires (you will be out of the newMail event by then), you can open the message and process it.

Related

How to make Keycloak 20.0.1 send an e-mail when a user is blocked due to too many failed login attempts?

I want Keycloak to send an e-mail to a user whenever a user is blocked due to too many failed login attempts (see section Realm Settings -> Security defenses -> Brute force detection).
The event in question has the following properties:
Error (org.keycloak.events.Event#getError) = user_temporarily_disabled
Type (org.keycloak.events.Event#getType) = LOGIN_ERROR
How can I do that, i. e. make Keycloak send an e-mail to the user when such event occurs?
Known ways to implement it
One obvious way to do it is to write a class that implements the org.keycloak.events.EventListenerProvider interface, detect the event in its onEvent method and trigger sending of the e-mail at some custom server (i. e. send a request to that server and it will contact an SMTP server).
Second is a variation: Detect the event in the same method and somehow make Keycloak send the e-mail using Keycloak SMTP settings ("Realm settings -> Email -> Connection & Authentication").
The screenshot in this answer made met think (possibly wrongly) that there may be a way to make Keycloak send emails upon the occurrence of certain events "out of the box," i. e. without writing custom event listeners.
Update 1: If someone else wants to do this, I recommend to look at this answer. The code below worked for me.
RealmModel realm = this.model.getRealm(event.getRealmId());
UserModel user = this.session.users().getUserById(event.getUserId(), realm);
if (user != null && user.getEmail() != null) {
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>" + user.getEmail());
org.keycloak.email.DefaultEmailSenderProvider senderProvider = new org.keycloak.email.DefaultEmailSenderProvider(session);
try {
senderProvider.send(session.getContext().getRealm().getSmtpConfig(), user, "test", "body test",
"html test");
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Keycloak does indeed support sending emails for events out of the box. However, it can only be configured by event (LOGIN_ERROR), and not by further filtered types (user_temporarily_disabled).
For this, you will need to implement your own EventListener, but it should be easy to heavily copy code from Keycloak's existing EmailEventListener, which you can find here: https://github.com/keycloak/keycloak/blob/main/services/src/main/java/org/keycloak/events/email/EmailEventListenerProvider.java
In there, you'd change the implementation of L59 in onEvent(Event event) to check your two conditions (event type and error), rather than checking against some list of configured fixed events. Your event will be added to the currently running transaction, and when the transaction ends (in success or error), Keycloak will send an email via the SMTP settings that are configured in the realm.
If you want to customize the template and subject lines of the email, you'll have to provide your own freemarker templates in src/main/resources/theme-resources/templates/{html,text}. Both the html and text folder need to contain an .ftl file of the same name. Message keys for use in the template and the subject go in src/main/resources/messages/messages_{en,fr,de,...}.properties files.
With the template and messages configured, you can use one of the 2 send(...) methods available in the EmailTemplateProvider class

How to retrieve a whole mailbox with Spring Integration Mail

I'm trying to create a piece of code that would retrieve the whole content of an INBOX, using Spring Integration Mail.
By default, an ImapIdleChannelAdapter will only fetch recent, unseen, unanswered etc... emails.
So when I created my adapter, I tried to use a special strategy that would retrieve all emails without a given unique user flag (so basically, all the mails I haven't retrieve yet).
Here is my adapter:
Mail.imapIdleAdapter(imapUrl(user, pw, provider))
.javaMailProperties { p: PropertiesBuilder -> p.put("mail.debug", "false") }
.userFlag(uniqueFlag)
.shouldMarkMessagesAsRead(false)
.searchTermStrategy(GetAllMailsStrategy(uniqueFlag))
.shouldReconnectAutomatically(true)
.autoCloseFolder(false)
val integrationFlowBuilder = IntegrationFlows.from(imapIdleAdapter)
.handle { message -> onNewEmail(user, uniqueFlag, message as org.springframework.messaging.Message<Message>) }
val flow: IntegrationFlow = integrationFlowBuilder.get()
flowContext.registration(flow).register()
And here is my strategy:
inner class GetAllMailsStrategy(private val uniqueFlag: String) : SearchTermStrategy {
override fun generateSearchTerm(supportedFlags: Flags?, folder: Folder?): SearchTerm {
val userFlag = Flags()
userFlag.add(uniqueFlag)
return NotTerm(FlagTerm(userFlag, true))
}
}
This piece of code does work, on small inboxes. As soon as I try to retrieve mails from an inbox with thousands of mails, at some point it just stops (sometime with FolderClosedException, even though I set autoCloseFolder to false, and sometime without any exception or log...), and then won't retrieve missing emails even if I start it all over with the same unique user flag. As if all the mails where flagged even though I never retrieved them. It does work on all new incoming emails though...
Any idea on what strategy I should use? Is there a way to get all the mails once, without flagging them?
Should I use Spring mail only to get incoming new mail but something else for the task of retrieving all the mails once?
Thanks
I never did it, but I think you are right: you should use an ImapIdleChannelAdapter for new (in IMAP terms RECENT) message, and some other ImapMailReceiver instance for initial call with your custom SearchTermStrategy.
The folder might be closed for some other reason, e.g. too many messages too long processed.

Mirth: Alerts triggered by errors in JS-based database writer don't have access to {messageId}?

Using mirth version 3.8.1. I've set up an alert for a channel's errors. When errors come from the destination transformer (which is Javascript), the alert is able to access the {messageId} variable and pull the correct id. However, when an error originates in the Javascript-based database writer, the alert just returns '{messageId}' instead of the value.
I tried a bunch of things...
The global map is accessible from the alert, but putting a message id in there would get overwritten by another processing thread.
Other destination types - http sender, tcp sender, channel writer, and even a non-javascript-based database writer destination all work.
I even stripped the database writer code down to just:
var dbConn;
dbConn = DatabaseConnectionFactory.createDatabaseConnection('com.mysql.cj.jdbc.Driver','jdbc:mysql://host:port/dbname','','');
Do I just have to raise specific exceptions within the db writer code and raise alerts when those exceptions are hit, and send the message id in the error string?
You stumbled across a bug. I opened an issue and a fix.
If not for another bug that also neglects to provide the messageId, you should be able to use alerts.sendAlert('Custom Error Message'). alerts is an instance of AlertSender from the User API that mirth creates for you. I created a fix for that as well.
The only workaround I know of at this time to manually send an alert that includes the messageId is to call the EventController directly. The caveat is that this is technically not supported as part of a public API and usage could break in future versions without notice.
com.mirth.connect.server.controllers.ControllerFactory
.getFactory()
.createEventController()
.dispatchEvent(new com.mirth.connect.donkey.server.event.ErrorEvent(
connectorMessage.getChannelId(),
connectorMessage.getMetaDataId(),
connectorMessage.getMessageId(),
com.mirth.connect.donkey.model.event.ErrorEventType.USER_DEFINED_TRANSFORMER,
connectorMessage.getConnectorName(),
null, /* connectorType */
'A TEST ERROR MESSAGE',
null /* throwable */
)
);
This will work as written from a filter, transformer, Javascript Writer, or Database Writer in javascript mode. In other contexts, connectorMessage won't be defined and you'll have to provide some of those values in a different way. If you don't need the messageId and don't want to throw an exception, just use alerts.sendAlert(errorMessage) since that doesn't require calling unsupported internal classes.

Symfony Messenger: Send logged messenger errors per email (via swift_mailer)?

I've configured monolog to send errors via email as described in the symfony docs here: https://symfony.com/doc/4.3/logging/monolog_email.html
Works well with all errors happing during a request, as well as console command errors.
But it does not send emails for errors which occurred during the handling of a messenger message.
Errors are shown when running the consumer bin/console messenger:consume async -vv and they also show up in prod.log like this:
[2020-01-10 12:52:38] messenger.CRITICAL: Error thrown while handling message...
Thanks for any hints on how to set up monolog to get messenger errors emailed too.
In fact monolog swift_mailer type use SwiftMailerHandler
wish also implements reset interface and use memory spool by default wish keep all emails in buffer until it is destructed, so till the end of request :
onKernelTerminate
onCliTerminate
OR till reset method is called, which means that for messenger worker no emails will be send ever because ther's no instant flush - all of them will be kept in in-memory buffer, and probably lost if the process will be killed.
To solve this, you can just disable the default spool memory setting for swiftmailer.
Another solution is to flush your emails after WorkerMessageFailedEvent event gets fired, you can implement an event subscriber to do it for this.
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
use Symfony\Component\Messenger\Event\WorkerMessageHandledEvent;
use Symfony\Contracts\Service\ResetInterface;
/**
* Class ServiceResetterSubscriber.
*/
class ServiceResetterSubscriber implements EventSubscriberInterface
{
protected ResetInterface $servicesResetter;
public function __construct(ResetInterface $servicesResetter)
{
$this->servicesResetter = $servicesResetter;
}
public function resetServices(): void
{
$this->servicesResetter->reset();
}
public static function getSubscribedEvents(): array
{
return [
WorkerMessageFailedEvent::class => ['resetServices', 10],
];
}
}
Register your service with the right argument:
App\EventSubscriber\ServiceResetterSubscriber:
arguments: ['#services_resetter']
By the way without this (and without buffer limit) your app will leak and no emails will be sent ever.
Another trick:
Make sure that your message implements \JsonSerializable to get the message content in your logs, because messenger uses his monolog directly and its context serializer wish use json_encode for seriliazation.
That's why we need to customize their JSON representation when encoded is done with json_encode.

Outlook Addin Event handler clean up

I am having problems with the event handler in my office addin . Below is an example code i got from microsoft website to explain what i mean.
I have a manifest file that uses the on-send hook as well as a click-based event triggering.
My button calls appendMessageBodyOnClick and onsend i call appendMessageBodyOnSend. Both function primarily do the same thing. I never want to block sending emails regardless.
The problem is that the event object is not properly cleaned up i think.
Scenario 1
When i click my button ; which calls event.completed(), and then after i try to send the message, it says my app is blocking the message, but then when i try to send again it goes through.
Scenario 2
When i leave the subject empty and then send the message, as expected i am prompted that the subject is empty. If i cancel sending the message on this note and then click on my button, the message tries to send as though i clicked send.
I am supposing the is some sort or state clean up issue. What am i doing wrong here?
Function-File.js
function appendMessageBodyOnClick(event) {
// Append string to message body
event.completed();
}
// In the following example, the checkMessage function has
// been registered as an event handler for ItemSend.
function appendMessageBodyOnSend(event) {
// Append string to message body
event.completed({allowEvent = true});
}
Not sure if this will help, but I also have faced some seemingly inconsistent behavior while understanding how to signal that event is fully completed. Once I got my edge cases fixed, then it worked.
One suggestion: Appending string to message body should be an async function. Call the event.completed() from inside the callback function. (i.e: make sure when you are calling event.completed(), nothing else is pending -like another async result)
Something like the following:
Office.context.mailbox.item.body.setAsync("new body", function(asyncResult) {
// handle success and failure
event.completed()
});
Same would be for your scenario 2, make sure event.completed() is called at the very end.