Error message when sending email within a loop in BPM

,

Hello

I am trying to send a reminder email to buyers with a list of PO pending approval from a BPM. I manage to get all the info I need, but when I try to send the emails I get the following error message:

New transaction is not allowed because there are other threads running in the session.

Find my code below:

var PendingApproverList = (from row in Db.POApvMsg where row.Company == "RFL" && row.MsgType == "1" select row.MsgTo).Distinct();
if (PendingApproverList != null)
{
	string body = "";
	foreach (string buyerID in PendingApproverList)
	{
		// Get Email Address and Ful name of buyers
		string emailAddress = (from row in Db.PurAgent where row.Company == "RFL" && row.BuyerID == buyerID select row.EMailAddress).FirstOrDefault();
		string fullName = (from row in Db.PurAgent where row.Company == "RFL" && row.BuyerID == buyerID select row.Name).FirstOrDefault();		
		
		//write email body
		body = "Dear " + fullName + "," + System.Environment.NewLine + System.Environment.NewLine + "The purchase orders below are pending approval from you: " + System.Environment.NewLine ;

    var pendingPO = (from row in Db.POApvMsg where row.Company == "RFL" && row.MsgType == "1" && row.MsgTo == buyerID select row.PONum);
		foreach (var PONum in pendingPO)
		{
			body = body + PONum + System.Environment.NewLine;
		};
		
		body = body + System.Environment.NewLine + "Best Regards";
		
		// Email Creation
		var mailer = this.GetMailer(async: true);
		var message = new Ice.Mail.SmtpMail();
		var from = "Epicor10@xxx.com";

		var subject = "PO pending approvals";
		message.SetFrom(from);
		message.SetTo(emailAddress);
		message.SetBody(body);
		message.SetSubject(subject);

		mailer.Send(message);		

		//this.PublishInfoMessage(body ,Ice.Common.BusinessObjectMessageType.Information, Ice.Bpm.InfoMessageDisplayMode.Individual,"","");
	}
};

I believe the issue is that I try to send the email from inside a loop, but I cannot find a way around that.

Hope someone can help!

Fabien

1 Like

Is this code running Synchronous or Asynchronous?

You might be able to get by, by placing the email handling in a thread, spawning a new one for each mail

Thanks Chris.

I made the code Asynchronous and it worked!