how resolve Address Invalid exception - java

We tried to send mail using javax.mail. While sending mails we got following exception:
**sendMail - Message Sending Failed: Invalid Addresses;
nested exception is:
javax.mail.SendFailedException: 550 #5.1.0 Address rejected.2013-02-28 13:17:08,236**
What might be the problem?

It means that the receiving server does not recognise the mailbox (the part before the '#') of the e-mail address. It could be that it was misspelled, that it is simply a non-existing name, or it could even be that the receiving server was set to reject a message (e.g. spam) by replying with code 550.
Here is one of many pages that summarises the SMTP reply codes, and gives links to various relevant RFCs: http://www.greenend.org.uk/rjk/tech/smtpreplies.html.
EDIT: I need a bit more space to answer your question than the comments allow.
#RaghuKing, if you look at the Javadoc for javax.mail.SendFailedException, you will notice that you can call 3 methods on such an exception object (inside the catch block):
getInvalidAddresses() to get an array of addresses that are invalid and thus not sent to,
getValidSentAddresses() to get an array of addresses to which this message was sent succesfully, and
getValidUnsentAddresses() to get an array of addresses that are valid but to which the message was not sent to.
(Obviously, if one sends a message to multiple recipients, some may succeed and some fail, but the exception is thrown if there is at least one failure, regardless of how many successes. Obviously also if you are sending to only one address, you will have that one address in only one of these arrays, and it will probably NOT be in the ValidSent list.
These arrays will give you more information how to handle the exception, depending of the type of array an address is in. This will obviously depend on you application, but these might be reasonable suggestions:
Invalid Addresses: tell the user that the message was not sent because the address was wrong, for each invalid address in the list, and provide a way to correct the address, then try to resend to the correct address (or cancel if the user does not provide a different address);
Valid Sent Addresses: Don't resend;
Valid Unsent Addresses: Try to resend to these addresses. Sending probably stopped before getting to these addresses because of a previous incorrect address.
But in the end it is you who has to apply common sense, and perhaps experiment a little with the functions you don't understand until you understand them.

This code can print logs for invalid address(es):
try {
sender.send(message);
}catch (MailSendException me){
detectInvalidAddress(me);
}
private void detectInvalidAddress(MailSendException me) {
Exception[] messageExceptions = me.getMessageExceptions();
if (messageExceptions.length > 0) {
Exception messageException = messageExceptions[0];
if (messageException instanceof SendFailedException) {
SendFailedException sfe = (SendFailedException) messageException;
Address[] invalidAddresses = sfe.getInvalidAddresses();
StringBuilder addressStr = new StringBuilder();
for (Address address : invalidAddresses) {
addressStr.append(address.toString()).append("; ");
}
logger.error("invalid address(es):{}", addressStr);
return;
}
}
logger.error("exception while sending mail.", me);
}

Had experienced this same exception .I realized that i could not send email to unknown users . After consulting , i found out that our SMTP server was not an open mail relay server read Open mail Relay.

Related

Give some examples of TCP Connection Status in JT400 - JAVA

I'm tried to get AS400 TCP Connection Status. but i'm failed :( can anyone help me to do this. i'm new to JT400 java development. please help me friends.
i want to get IP address of a job
i want to get TCP Connection Status using that (1) IP address.
Please help me
Thank you!
Edit :
i got this class
com.ibm.as400.util.commtrace.TCPHeader
It's return this informations
getACKFlag()
getAckNum()
getCheckSum()
getCWRFlag()
getDataOffset()
getDstPort() ..etc
now i want to get this informations. its mean, how to get TCP status using this class.
Please help me
Thank You
To get the IP address of a job:
System.out.println("IP address " + job.getValue(job.CLIENT_IP_ADDRESS));
The commtrace classes are not real-time. They use a trace file which was created on the IBM i server at some earlier time. In order to create that trace file, see the Javadoc for com.ibm.as400.util.commtrace.CommTrace Basically you will need to run the IBM i commands STRCMNTRC, ENDCMNTRC and DMPCMNTRC. Then use commtrace.CommTrace to create a trace file formatted so that the other commtrace classes can read it.
EDIT: Add code snippet from commtrace.Format Javadoc
import java.util.*;
import com.ibm.as400.access.*;
import com.ibm.as400.util.commtrace.*;
public class TestCommTrace {
public static void main(String[] args) {
try {
Format f = new Format("/buck/linetrace");
FormatProperties fmtprop = new FormatProperties();
f.setFilterProperties(fmtprop); // Sets the filtering properties for this Format
f.formatProlog(); // Format the prolog
Prolog pro = f.getProlog();
System.out.println(pro.toString());
if(!pro.invalidData()) { // This is not a valid trace
Frame rec;
while((rec=f.getNextRecord())!=null) { // Get the records
System.out.print("Frame " + rec.getRecNum().toString()); // Print out the Frame Number
System.out.println(" time " + rec.getTime().toString()); // Print out the time
IPPacket p = rec.getPacket(); // Get this records packet
Header h = p.getHeader(); // Get the first header
if(p.getType()==IPPacket.IP4) { // If IP4 IPPacket
if(h.getType()==Header.IP4) { // If IP4 Header
IP4Header ip4 = (IP4Header) h; // Cast to IP4 so we can access methods
System.out.println(h.getName()); // Print the name
System.out.println("IP4 src:"+ip4.getSrcAddr() + " dst:" + ip4.getDstAddr());
System.out.println(ip4.printHexHeader()); // Print the header as hex
// Print a string representation of the header.
System.out.println(ip4.toString()); // hex string
//System.out.println(ip4.toString(fmtprop)); // very detailed
while((h=h.getNextHeader())!=null) { // Get the rest of the headers
if(h.getType()==Header.TCP) { // If its a TCP header
TCPHeader tcp = (TCPHeader) h; // Cast so we can access methods
System.out.println("TCP src:" + tcp.getSrcPort() + " dst:" + tcp.getDstPort() + " checksum:" + tcp.getCheckSum());
System.out.println(tcp.toString()); // hex string
//System.out.println(tcp.toString(fmtprop)); // very detailed
} else if(h.getType()==Header.UDP) { // If its a UDP header
UDPHeader udp = (UDPHeader) h; // Cast so we can access methods
System.out.println("UDP src:" + udp.getSrcPort() + " dst:" + udp.getDstPort());
System.out.println(udp.toString());
}
}
}
}
}
f.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
EDIT: Some more detailed information
1) On the IBM system, someone with special permission must run STRCMNTRC and collect communications trace information. This trace file contains all of the TCP packets that flowed between the IBM system and the outside world. For example, if the trace runs for an hour, it will collect every packet the system sent and received during that hour. The trace data is stored in a format that is special and can not be directly read.
2) To make the trace data readable, use the DMPCMNTRC command. This will create a flat text stream file out of the trace data. This data needs to get to your PC so that the com.ibm.as400.util.commtrace classes can work on it.
3) On your PC, run com.ibm.as400.util.commtrace.CommTrace. This will create a file in a simple text form that com.ibm.as400.util.commtrace can process. I put mine in /buck/linetrace. It is important to understand that there are hundreds or thousands of packets in this log, and every one of them has the information you ask about in the question. There is not one single ACK flag, there are many hundreds of them. In order to understand what is happening, your program will need to read a packet, get the header, then the status, get the data and then read the next packet, and the next and the next, all the way through them all.
4) In order to filter by IP address, you can either use setFilterProperties() or have your code check the IP addresses in each packet header and only process the headers you want to.
It is important to understand that the 'status' you are looking for is not a property of an IP address, it is a property of a TCP packet. There is no way to ask the system for the ACK flag of an IP address because there is no such property to be returned. The only way to get these things is to record them at the instant the packet is read or written by the system.
I would be very surprised if you really need these flags; almost no one does. Usually, 'connection status' means a way to determine if the machine is running or not. ping is the typical way to answer that question, but not all machines will answer a ping. For those machines, the best way is to try to connect to the machine and port you want to test.

SMPP Invalid destination address submitting international message

Good day guys!. I'm having a problem trying to submit an international sms vía SMPP (using Logica Java library). I'm gonna summarize the tests I've done. I'm using WireShark to monitor SMPP related activities.
(Working)
//Connect and stablish session
Connection conn = new TCPIPConnection(providerAddress, port);
Session session = new Session(conn);
BindRequest breq = new BindTransmitter();
breq.setSystemId(user);
breq.setPassword(pass);
breq.setSystemType("CMT");
breq.setInterfaceVersion((byte)34);
breq.setAddressRange((byte)0x01, (byte)0x01,null);
Response resp = session.bind(breq);
//Create message
SubmitSM msg = new SubmitSM();
msg.setDestAddr((byte)1, (byte)1, "58412014XXXX");
msg.setSourceAddr((byte)1, (byte)1, "58412014XXXX");
msg.setShortMessage("Test from tedexis","ISO-8859-1");
//Here we submit message
session.submit(msg);
//Disconnect
session.unbind();
Result: Message is delivered correctly. Here we validate credentials are valid, and notice the source and destination addresses are the same
(Failing) The code remains the same except for the message destination address which is now set for an INTERNATIONAL PHONE NUMBER
msg.setSourceAddr((byte)1, (byte)1, "1321237XXXX");
Result: Fails, checking WireShark I observe the following exception during the submit:
SMPP Submit_sm - resp: "Invalid destination address"
We may think that our credentials are not valid for international deliveries but we are currently using these credentials delivering international messages through their webservice interface.
I must be missing a configuration setting or wrongly setting one already, but I ran out of ideas, if anyone can point me in the right direction I would be glad.
First, you dont have to set your address range since you're binding as a transmitter, because the address range is used to inform the SMSC that this 'receiver' session will handle MO messages from the desired address range.
As for sending to international numbers, i'm not into logica's API but i'm pretty sure that you're missing to set the destination address ton to 1 (international number) and the destination address npi to 0 (Unknown) or 1 (ISDN) and retry the sending.
If the error persists, you'll have to call your provider, it is possible that they gave you the permission to send to international numbers through webservice only.

JavaPNS error handling - contradiction in the documentation?

In the JavaPNS docs, I see this:
To find out if a push was successfully sent to Apple and that Apple did not return any error-response packet, simply invoke the pushedNotification.isSuccessful() method. A notification might not be successful if any of these conditions occur:
the library rejected the token you provided because of obvious specs violations (ex: token not 64-bytes long, etc.)
the library rejected the payload you provided because of obvious specs violations (ex: payload too large, etc.)
a connection error occurred and the library was not able to communicate with Apple servers
an error occurred with your certificate or keystore (ex: wrong password, invalid keystore format, etc.)
a valid error-response packet was received from Apple servers
and many other possible errors...
But the code snippet provided then does
for (PushedNotification notification : notifications) {
if (notification.isSuccessful()) {
/* Apple accepted the notification and should deliver it */
System.out.println("Push notification sent successfully to: " + notification.getDevice().getToken());
/* Still need to query the Feedback Service regularly */
} else {
String invalidToken = notification.getDevice().getToken();
/* Add code here to remove invalidToken from your database */
/* Find out more about what the problem was */
Exception theProblem = notification.getException();
theProblem.printStackTrace();
/* If the problem was an error-response packet returned by Apple, get it */
ResponsePacket theErrorResponse = notification.getResponse();
if (theErrorResponse != null) {
System.out.println(theErrorResponse.getMessage());
}
}
}
Which seems to imply that isSuccess() == false means an unrecoverable error, and that the device token is not valid.
However, the list of possible reasons did say that isSUccess() might be false due to a legitimate error packet being returned. I don't know, but I imagine one might be returned if Apple failed to send the notification due carrier issues, for example, which means the token is not necessarily invalid.
Is the correct way to read this, then, that isSuccess() == false is an unrecoverable error when sending a message, but not one that requires an exception, like a keystore fail or an inability to connect to the servers at all?
In other words - id isSuccessful() == false, should I really delete the device token from my DB as suggested? The snippet says yes, but the documentation seems to me to suggest otherwise...
Links: http://code.google.com/p/javapns/wiki/ManagingPushErrors
Thanks in advance to anyone who has braved this long, rambling question.
-- Snorkel
The documentation says that you are correct. Technically it means the push failed, but not that it failed because of an exception. It could have failed because of a legitimate failure. (I define legitimate failure as we successfully connected, there were no obvious defects with the message, but the server declined to accept it.) The key line is the following:
IE To find out if a push was successfully sent to Apple and that Apple did not return any error-response packet, simply invoke the pushedNotification.isSuccessful() method.
Your whole question seems pretty roundabout though. In a simple sense, your push failed. Does the distinction between an exception and a failure really matter? Either way its unrecoverable and you need to check the logs to see exactly what happened.

Java mail bounced back mail's address

I have to send messages to many clients. But many of them bounce back. I want a list of those email addresses. How can I get that list from my Java application?
Make a special email address bounced#yourdomain.com where you will capture all bounced emails for analysis.
Add the following header to your sent emails:
Return-Path: <bounced#yourdomain.com>
Now the emails are going to bounce back to that address.
Read emails at that address from your java program from time to time, for example via IMAP (or depending on your server via a notification interface/whatever), and when you see an email address record it in your database
Note that if you are doing a newsletter app, you should not blacklist the email from the first time, but make count it's bounces, and blacklist it after 3-4 bounces (some people set their email to bounce when they go in vacation and such, so they need special taking care of).
I solve this question using
SMTPMessage msg = new SMTPMessage(getSession());
msg.setEnvelopeFrom(bounceAddr);
Please see the javamail doc and see it:
void com.sun.mail.smtp.SMTPMessage.setEnvelopeFrom(String from)
Set the From address to appear in the SMTP envelope. Note that this is different than the From address that appears in the message itself. The envelope From address is typically used when reporting errors. See RFC 821 for details.
If set, overrides the mail.smtp.from property.
Parameters:
from the envelope From address

E-mail sent with commons-mail is *sometimes* not received. How can I troubleshoot?

When I send out an e-mail and it isn't received, how can I figure out what the cause of the problem is?
My app sends e-mails through SMTP using the Apache commons-mail library. For testing purposes, I am using the gmail SMTP server. (Our production app uses an internal server on our network).
In one case on the test server, I have a batch job that generates 5 e-mails with attachments. Some e-mails are received and others are marked as sent, but never appear in my inbox. There doesn't seem to be a pattern to which e-mails are received and which ones silently vanish.
The code that sends and checks for errors looks like this:
final Mail mail = ...;
//The Mail class is our app's mail object, which provides data used to generate the MIME e-mail and record the results.
final MultiPartEmail email = ...;
try {
email.setSentDate(mail.getDateSent());
email.send();
}
catch (EmailException ee) {
success = false;
mail.setDateSent(null);
getLog().error("Mail not sent: ", ee);
if (ee.getMessage().indexOf("receiver address required") != -1) {
mail.setErrorMessage(ee.getMessage());
getLog().error(mail.toString());
}
}
In the debugger, I determine that no exception is thrown.
My first guess was that the attachment size is too large; but, gmail supposedly supports 25MB attachments, and my largest attachment is 14.3 MB. In some cases when I run the entire batch of 5 e-mails, the e-mail with the largest attachment gets through, and the smaller ones disappear.

Categories

Resources