How to handle error in Messaging.sendEmail()? - error-handling

I wrote code to send email. It works fine but my goal is:
When someone sent to non-existing email address, I want to log the result as 'false' or 'failure' etc (and when email address is valid, just say 'success')
I've tried 2 things with the code below.
provided non-email string 'foo#!'
provided non-existing email address 'thisdoesnotexistignsdfkjsdf#gmail.com'
result:
Execute case 1 caused code to go into catch block thus outputting error message on the html page which is expected.
Execute case 2 caused code to return 'ok sent!'
And after few minutes I received email that delivery failed.
My guess is SendEmailResult object's isSuccess() is not really responsible for non-existing email address check. It only cares if the email is fired???
Is there any way to log if the email account does not exist so I can log such occasion in my Apex code?
try {
Messaging.SendEmailResult[] resultMail = Messaging.sendEmail(new
Messaging.SingleEmailMessage[] { mail });
resultMail[0].getErrors();
//display success or error message
if (resultMail[0].isSuccess()) {
response = 'ok sent!';
} else {
response = resultMail[0].getErrors().get(0).getMessage();
}
//log
boolean isSuccess = resultMail[0].isSuccess();
Integer out = EmailLogger.logEmailSent(this, isSuccess);
} catch (System.EmailException ex) {
system.debug('============== email exception caught!!!=============');
response = ex.getMessage();
}

Email (SMTP) is a store and forward protocol, at the time of sending, you can't tell that the destination email address is non-existant, you can only find that out once the message actually gets to the final destination server.

if there was a way to find email address whether it really exists or not, a spammer might have tried brute force attack - trying every possible combination of email and sending infinite spams :)
thank god, that's not possible.

Related

How to I get the detail (custom error message) returned with a bad request status code? So that I can do an ASSERT on it

Hi so I am setting up some Integration tests (using Xunit) and I would like to run an Assert to check whether the correct custom error message is returned.
This is the data I need to get is in the following response see image...
detail: "Username must be unique" Don't worry this message will be modified to be more useful later on I am just wanting to get it working first
Required Info
This is the current code...
//Act
response = await _httpClient.PostAsync("CompleteUserSetup", formContent);
//Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode) ; //Bad request should be returned
//TODO: check custom error message is correct
So hoping for...
ASSERT.Equal("Username must be unique", some code to get detail from response)
Okay so I figured out how to get the data I needed. I just needed to convert the result into an object and then I was able to pull the detail data that I needed.
var resultModel = await System.Text.Json.JsonSerializer.DeserializeAsync<Result>(response.Content.ReadAsStream(), JsonSerializerHelper.DefaultDeserialisationOptions);
var errorMessage = resultModel.detail;

Delay in sending email in ASP.NET CORE

Hi am building a web application using blazor which sends email activation link to registered users, email activation is is being sent but the problem here it takes too long(approximately 5 minutes) for the registered user to receive the activation link. here is my code.
my interface class
public interface IEmailServices
{
Task SendEmailAsync(string toAddress, string subject, string body);
}
My mail Sender Class
public class EmailSender : IEmailServices
{
public async Task SendEmailAsync(string emailDestination, string subject, string htmlMessageBody )
{
MailMessage ms = new MailMessage("myemail#domain.com", emailDestination, subject,htmlMessageBody);
ms.IsBodyHtml = true;
string user = "myemail#domain.com";
string passcode = "mypassword";
SmtpClient smtpServer = new SmtpClient("mail.domain.com");
smtpServer.Credentials = new System.Net.NetworkCredential(user, passcode);
try
{
await smtpServer.SendMailAsync(ms);
}
catch (Exception ex)
{
throw ex;
}
}
}
Here's where am sending the message
//Generate Email confirmation link
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
I want the message to be sent immediately upon registration so user can confirm email.. is there something am missing thanks in advance
You don't appear to be doing anything that would generate a huge email, so this shouldn't be taking very long. A suggestion I can make is to set up your app in a test environment, with the SMTP connection set to an email account you have access to in your configuration. (Even a gmail account would work, but you'd have to set the Gmail security appropriately.) Then, run your app in debug mode with a breakpoint at await smtpServer.SendMailAsync(ms);, and then continue (F5 in VS) forward from that call to execute SendEmail Async() and let the app continue running. This will allow confirmation that the email sent, and also give you some insight into if the issue is ahead of sending the email entirely or not. Make sure you are signed in to the email account you are testing with before you start, then hop into the email account Sent folder and check that it shows the sent email. If the email takes a long time to send, the issue is in your SMTP connection from the app. If it sends in short order but still takes forever to arrive at the recipient, it has to do with the email account(s) or the clients hooked up to them (think the Send / Receive interval in Outlook set too long), but not necessarily your application. That should help you pin the problem down so you know what you are dealing with.

Socket.io - Is there a way to save socketid to prevent a new one being generated

After a connection to the socket.io server a socket.id is given for the connection. When the socket connection has not been used after some time a new socket id is generated.
I have read a lot of tutorials that do a "hello world" connection that just gets you connected, but, there is not much literature on messaging peer-to-peer/group. The docs give a 3 line paragraph on rooms/namespaces and every question related to this is just given a link to the same 3 line paragraph.
I understand that you can create and object/array of chats(in this example). For this example, let's say it is an object. That Object looks something like this:
const connections = {
"randomSocketID1": {
recipient: "Mom",
messages: [Array of Objects]
//more information
}
}
I then send a message to randomSocketID1 --> 'Hello'. Then next day I want to send another message to "Mom". Is that socketID going to be the same OR AT LEAST will "randomSocketID1" be updated under the hood, to its updated ID(which sounds improbable)? Is the regeneration of the socketID a product of garbage collection or a socket/engine/websocket protocol?
thanks for any clarification
So I was still unable to find an actual answer to this and by the 0 responses i see that no one knows. So what I have done in order to make sure that user and socket id are maintained is whenever a user enters the component that connects to the socketio server an automatic 'update-user' is emitted and the back end then just finds the user and assigns it the value.
So I have something like this:
chat.component.ts:
ngOnInit(){
this.socket.emit('update-user', 'Ctfrancia');
}
then in the back end:
const users = {};
io.on('connection', socket => {
socket.on('update-user', user => {
if (user in users) users[user] = socket.id;
else users[user] = socket.id
});
});

How to get error or success result from Acumatica Web service api?

//LoginResult loginResult = context.Login("user","pass");
//if (loginResult.Code != ErrorCode.OK)
//Get Schema
//Insert
//Add fields values
//....
O301000.Actions.CopyOrder,
O301000.Actions.Save,
O301000.OrderSummary.OrderNbr
Submitresult = O301000.context.Submit(cmds);
How do I know if there was an error when inserting/saving the Order (or any other file)?
I just can find a value 'Submitresult.ErrorCode' like in the Login Result.
Mean while a have solve the issue, when inserting, by looking for the 'O301000.OrderSummary.OrderNbr' not null value.
But that does not works when updating a record.
You should always use a
try{Submitresult = O301000.context.Submit(cmds);}
catch(Exception ex){Console.WriteLine(ex.Message);}
when making these calls. If the SOAP calls returns an error, than the message is passed to the Exception object.

Bot api, how i can get last message or chat history?

I want implement some functional like user send me a message and I reply to him with my (bot) latest message from chat history.
As you can see in the Telegram Bot API Documentation you can use sendMessage to send a message to the user.
When you receive a message, look for the chat or the from parameter in the JSON (depends if you want to answer to the person when it's a group chat or not). You can use the id parameter of the chat or from to send the message.
So the first parameter for your sendMessage would be chat_id=message.chat.id
You don't need the parse_mode, disable_web_page_preview and reply_markup for this example.
As you want to reply to the message of the user you may want to set the reply_to_message_id to the id of the received message.
reply_to_message_id = message.message_id
Last but not least, you want to set the text parameter. If I understand it correctly, your program will send the last received message.text to the user.
So what you want to do is, as soon as you get a message, save it.
Message oldMessage = message
And when you send the Message to the user use the old messages text property as the text.
text = oldMessage.text
Alright to sum it up here is the pseudocode of the function that will happen as soon as you receive a message:
Message oldMessage = null;
public void NewMessage(Message message){
int chat_id = message.chat.id;
int reply_to_message_id = message.message_id;
String text = "There is no old Message"; //fallback value
if(oldMessage != null){
text = oldMessage.text;
}
//Send Message in this example only has 3 parameters, and ignores the
//not used ones
SendMessage(chat_id,text,reply_to_message_id);
oldMessage = message; //store the received message for future answering
}
As you store the whole message in oldMessage you could also set the text you will send to something like this:
String text = oldMessage.from.first_name+": "+oldMessage.text;
if you simply want to reply on users message you need this function:
public void sendMsg(Message message, String text){
SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(text);
try{
setButtons(sendMessage);
sendMessage(sendMessage);
}catch (TelegramApiException e){
e.printStackTrace();
}
}