Class MessagingException not working as I think it should - email

I'm developing a web application that sends an email and has to check, that, in fact this mail has been delivered from my application side as much as possible in few seconds (I don't think you can do more than getting that the email has been delivered to email server, if that email server later cannot later send that email to the user that uses it because it has its inbox full or another situation like this, I think it cannot be helped, although if there's some way I'd like to know about it).
Anyway one thing I think could be checked without problems is if the email address doesn't exist as that gives an inmediate response, according to what I've read this could be done with class MessageException, but I've the following code:
String email=Utils.parseString(req,"email");
[....]
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.EnableSSL.enable","true");
Session s = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(s);
try {
InternetAddress from = new InternetAddress(emailadressthatworks);
message.setFrom(from);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
try {
InternetAddress to = new InternetAddress(email);
message.addRecipient(Message.RecipientType.TO, to);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
resp.sendRedirect("webpage.jsp");
return;
}
try {
message.setSubject("Subject");
message.setText("message");
Transport.send(message);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
resp.sendRedirect("webpage.jsp");
return;
}
[....]
And whatever random String I asign to email it never throws an MessagingException in Transport.send(message); so I can redirect it to another jsp web page when I think it should according to what I have read.
Might I be missing something or is it that this class cannot detect that things?
Thanks for your help.

Use the strict InternetAddress constructor and call message.saveChanges() to perform the validation. See
Content-Type syntax check throws exception too late for more details.

See this JavaMail FAQ entry.
Also, it's up to your mail server whether it tries to detect some kinds of errors immediately or whether it queues all requests and only checks for errors later.

Related

Why can not I read bytes from the TcpClient in C#?

Why can not I read bytes from the TcpClient in C#?
Here is the error I am getting:
Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.
Here is how I start my TcpClient:
public static async void Start()
{
TcpListener server = null;
try
{
server = new TcpListener(IPAddress.Loopback, 13000);
server.Start();
var client = await server.AcceptTcpClientAsync();
var stream = client.GetStream();
var bytes = Convert.FromBase64String("ABCD");
await stream.WriteAsync(bytes, 0, bytes.Length);
client.Close();
}
catch (Exception e)
{
throw;
}
finally
{
if(server != null)
{
server.Stop();
}
}
}
Here is how I run a request to the TcpClient:
try {
var response = (new HttpClient()).GetByteArrayAsync("http://localhost:13000").Result;
return Convert.ToBase64String(response);
} catch(Exception e) {
throw;
}
The return Convert.ToBase64String(response); line is never reached. While I see the quoted above error message inside the Exception e if I hit a breakpoint on the throw line.
Also, during debug the Start() method completes just fine. I.e. it starts, then wait for a request, gets a request, writes to the TclClient and at the end runs the server.Stop(); command.
I am expecting my code to work, because I took it and modified from the official documentation over here.
I tried to check out a few resources which would tackle my exception, but none of them did help.
E.g. I tried to use the question.
First answer tells nothing useful actually, but just plays around with words and at the end states that one can do nothing about the exception (please, correct me if I am missing a point in the answer).
And the second answer tells an impossible in my case problem. Because, I am sure there is nothing running on the 13000 port.
Your client code is using HttpClient, which sends an HTTP request and expects an HTTP response. But your server is not an HTTP server, it is just a plain TCP server, so the client is likely to fail and forcibly close the connection when it doesn't receive a properly formatted HTTP response.
The "official documentation" whose example you modified is not using HttpClient at all, it is using TcpClient instead.
If you want to use HttpClient in your client, then you should use HttpListener instead of TcpListener in your server.

I want to send additional parameter with message by Smack API client in ejabberd

I am using Ejabberd as XMPP server and creating xmpp client in smack API.I want to send additional parameter with message.
My code is below :
public static void main(String[] args) throws SmackException,IOException,XMPPException {
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setResource("Smack")
.setSecurityMode(SecurityMode.disabled)
.setServiceName("localhost")
.setHost("localhost")
.setPort(Integer.parseInt("5222"))
.build();
AbstractXMPPConnection conn = new XMPPTCPConnection(config);
try {
conn.setPacketReplyTimeout(10000);
SASLAuthentication.unBlacklistSASLMechanism("PLAIN");
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
//SASLAuthentication.
conn.connect();
conn.login("test1#localhost","123456");
System.out.println("login successfull");
Message message = new Message();
String stanza = "i am vip";
message.setBody(stanza);
stanza+= "<type>.jpg</type>";
ChatManager manager = ChatManager.getInstanceFor(conn);
manager.createChat("vipul#localhost").sendMessage(message);
message.setBody(stanza);
System.out.println("Message Sent");
} catch (Exception e) {
e.printStackTrace();
}
}
By this code i am able to add type in xmpp stanza but i think it is not preferable way.So i need help to send additional parameter with message.
If i get solution this will be appreciated.
Thanks !!
you can add additional parameter like that-
Message message = new Message();
String stanza = "i am vip";
message.setBody(stanza);
message.addBody("customtag","Custom tag value");
message.addBody("customtag1","Custom tag value1");
and you can get it like-
String customtageValue= message.getBody("customtag");
for more detail check this link

Unable to get xmpp muc room information in android

I am using asmack library for my chat application.I am using below described code after successful login for getting Muc room information:
MultiUserChat mMultiUserChat = new MultiUserChat(connection,"VjNewMoiosandroid#conference.chat");
mMultiUserChat.join(USERNAME);
try {
if (mMultiUserChat.isJoined()==true) {
RoomInfo roomInfo=mMultiUserChat.getRoomInfo(connection,"VjNewMoiosandroid#conference.chat");}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I get this error while getting room information ,while i debug and check i am getting room information in log but nothing comes in roomInfo.
10-10 08:55:12.388: W/System.err(1821): java.lang.ClassCastException:
org.jivesoftware.smack.util.PacketParserUtils$2 cannot be cast to
org.jivesoftware.smackx.packet.DiscoverInfo 10-10 08:55:12.428:
W/System.err(1821): at
org.jivesoftware.smackx.ServiceDiscoveryManager.discoverInfo(ServiceDiscoveryManager.java:600)
10-10 08:55:12.458: W/System.err(1821): at
org.jivesoftware.smackx.ServiceDiscoveryManager.discoverInfo(ServiceDiscoveryManager.java:552)
10-10 08:55:12.478: W/System.err(1821): at
com.demo.xmppchat.CopyOfXMPPChatDemoActivity.getRoomInfo(CopyOfXMPPChatDemoActivity.java:469)
My chat room information i received in log
10-10 15:38:10.133: D/SMACK(26035): 03:38:10 PM RCV (1107887640): <iq
from='VjNewMoiosandroid#conference.chat' to='14393671556301070000#chat/Smack'
id='VWaeO-6' type='result'><query xmlns='http://jabber.org/protocol/disco#info'><identity
category='conference' type='text' name='VjNewMoiosandroid'/><feature var='
http://jabber.org/protocol/muc'/><feature var='muc_public'/><feature
var='muc_persistent'/><feature var='muc_open'/><feature var='muc_semianonymous'/><feature
var='muc_moderated'/><feature var='muc_unsecured'/><x xmlns='jabber:x:data'
type='result'><field type='hidden' var='FORM_TYPE'><value>
http://jabber.org/protocol/muc#roominfo</value></field><field label='Room description'
var='muc#roominfo_description'><value></value></field><field label='Number of occupants'
var='muc#roominfo_occupants'><value>1</value></field></x></query></iq>
I was using old asmack jar that is my issue ,I made some changes i used MultiUserChat class getRoomInfo() Method directly in my class
MultiUserChat mMultiUserChat = new MultiUserChat(connection,"VjNewMoiosandroid#conference.chat");
mMultiUserChat.join(USERNAME);
try {
if (mMultiUserChat.isJoined()==true) {
String roomInfo=getRoomInfo(connection, "VjNewMoiosandroid#conference.chat");}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I made one method as below
public static String getRoomInfo(Connection connection, String room)
throws XMPPException {
String roomInfo="";
try {
ServiceDiscoveryManager serviceDiscoveryManager=new ServiceDiscoveryManager(connection);
DiscoverInfo info = serviceDiscoveryManager.discoverInfo(room);
roomInfo=info.toXML();
} catch (XMPPException e) {
// TODO: handle exception
Log.e("xmpp", e.toString());
}
return roomInfo;
}
Do this way
Replace this line
RoomInfo roomInfo=mMultiUserChat.getRoomInfo(connection,"VjNewMoiosandroid#conference.chat");
With this
RoomInfo roomInfo=MultiUserChat.getRoomInfo(connection,"VjNewMoiosandroid#conference.chat");

JavaMail Get Message for Undelivered Emails (to Gmail or Ymail)

I'm trying to build an app to send bulk report emails to many addresses with various hosts. I'm using Javamail and well, I'm still learning it though.
I found an example and try sending emails with my company server as host (let's say xyz company).
here is the sample code
package mailexample;
import javax.mail.*;
import javax.mail.internet.*;
public class MailExample {
public static void send(String smtpHost, int smtpPort,
String from, String to,
String subject, String content) {
try {
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", ""+smtpPort);
Session session = Session.getDefaultInstance(props, null);
//Store store = session.getStore();
//Folder folder = store.getFolder("INBOX");
//System.out.println(folder.getMessage(1));
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);
Transport.send(msg);
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
try {
send("mail.xyz.ac", 25, "asdf#xyz.ac", "qwer#xyz.ac",
"title", "content");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
It works fine and I get an error stacktrace when the address is invalid.
But that is only happen if I send an email to the same server/host which is mail.xyz.ac.
If I send an email to some random gmail or ymail addresses (that likely don't exist), my app return success message but nothing happened after that, only a message (like mailer-daemon in gmail) in sender inbox that said it is not delivered.
The problem is, I need to store that message in my database for further notice.
Is it possible to get that message from my app?
The JavaMail FAQ is your friend while learning JavaMail. This entry and this entry address your question. Also, be sure to read the entry about common mistakes.

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?