Plivo SMS is not being sent and getting error in Java - java

I am integrating Plivo SMS API with my java web application. I want to send messages through my application. I am referring to https://www.plivo.com/docs/getting-started/send-a-single-sms/ link.
Below is the code snippet:
String authId = "{my Auth_id}"; //Your Authentication ID
String authToken = "{my auth Token}"; //Your authentication code
RestAPI api = new RestAPI(authId, authToken, "v1");
LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();
parameters.put("src", "+44*******"); // Sender's phone number with country code
parameters.put("dst", "+91*******"); // Receiver's phone number with country code
parameters.put("text", "Hi, text from Plivo"); // Your SMS text message
try {
// Send the message
MessageResponse msgResponse = api.sendMessage(parameters);
// Print the response
System.out.println(msgResponse);
// Print the Api ID
System.out.println("Api ID : " + msgResponse.apiId);
// Print the Response Message
System.out.println("Message : " + msgResponse.message);
if (msgResponse.serverCode == 202) {
// Print the Message UUID
System.out.println("Message UUID : " + msgResponse.messageUuids.get(0).toString());
} else {
System.out.println(msgResponse.error);
}
} catch (PlivoException e) {
System.out.println(e.getLocalizedMessage());
}
I tried to run this code using console application as well as web application.I am getting exception "com.plivo.helper.exception.PlivoException: Connection to https://api.plivo.com refused". What is wrong with my code? Am I missing anything here?

Plivo Sales Engineer here.
Please check your firewall settings to ensure that it's not blocking any traffic. Also, are you using a web proxy? If yes, make sure that your application is using this proxy to handle connections.

Related

How To Detect An Email Address Is Real

IMPORTANT
I have been blocked by hotmail services. There is a control mechanism
called spamhaus which kicked me out. I'm stuck right now.
I am trying to detect an email address is valid and if its valid then check if this email address potentially used (I know that its not certain). For example, lets assume that there is a website with domain myimaginarydomain.com. If I run code below, I guess it won't fail because domain address is valid. But nobody can take an email address with that domain.
Is there any way to find out that email address is valid? (In this case its invalid)
I don't want to send confirmation email
Sending ping may be useful?
public class Application {
private static EmailValidator validator = EmailValidator.getInstance();
public static void main(String[] args) {
while (true) {
Scanner scn = new Scanner(System.in);
String email = scn.nextLine();
boolean isValid = validateEmail(email);
System.out.println("Syntax is : " + isValid);
if (isValid) {
String domain = email.split("#")[1];
try {
int test = doLookup(domain);
System.out.println(domain + " has " + test + " mail servers");
} catch (NamingException e) {
System.out.println(domain + " has 0 mail servers");
}
}
}
}
private static boolean validateEmail(String email) {
return validator.isValid(email);
}
static int doLookup(String hostName) throws NamingException {
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
Attributes attrs =
ictx.getAttributes(hostName, new String[]{"MX"});
Attribute attr = attrs.get("MX");
if (attr == null) return (0);
return (attr.size());
}
}
There is no failsafe way to do this in all cases, but, assuming the server uses SMTP then https://www.labnol.org/software/verify-email-address/18220/ gives quite a good tutorial on one method that may work.
The method used in the tutorial relies on OS tools, so you will need to ensure they exist before using them. a ProcessBuilder may help. Alternatively, you can open a socket directly in code and avoid using OS-dependent tools.
Essentially, you find out what the mail servers are (using nslookup), then telnet to one of the mail servers and start writing an email:
3a: Connect to the mail server:
telnet gmail-smtp-in.l.google.com 25
3b: Say hello to the other server
HELO
3c: Identify yourself with some fictitious email address
mail from:<labnol#labnol.org>
3d: Type the recipient’s email address that you are trying to verify:
rcpt to:<billgates#gmail.com>
The server response for rcpt to command will give you an idea whether an email address is valid or not. You’ll get an “OK” if the address exists else a 550 error
There really is no sensible way except trying to send a notification with a token to the address and ask the other party to confirm it, usually by visiting a web-page:
the recipients MX may be unavailable at the moment but come back online later, so you cannot rely on a lookup in real time;
just because the MX accepts the email doesn't mean that the address is valid, the message could bounce later down the pipe (think UUCP);
if this is some kind of registration service, you need to provide some confirmation step anyway as otherwise it'd become too easy to subscribe random strangers on the internet that do not want your service.

Google app engine not sending mail despite calls appearing in Quota details

I have spent the weekend playing with Google App Engine and Google Web Toolkit and have got along pretty well and built a simple app.
The stumbling block seems to be sending e-mails. My code is:
private void sendOffenderMail( OffenceDetails offence )
{
if( offence.email == null || offence.email.equals("") )
{
return;
}
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
String msgBody = "You have been added to the list";
if( offence.notes != null && !offence.notes.equals( "" ) )
{
msgBody += "\n\nThe following notes were included:\n\n" + offence.notes;
}
Message msg = new MimeMessage(session);
try {
msg.setFrom( new InternetAddress(<gmail account belonging to project viewer>, "List Admin") );
msg.addRecipient(
Message.RecipientType.TO,
new InternetAddress (offence.email, offence.name )
);
msg.setSubject("You've been added to the list...");
msg.setText(msgBody);
Transport.send(msg);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
When I run this on the development server logs get printed out in the console about the mail that would have been sent.
When I deploy to app engine and try there nothing happens, I don't get any mail.
If I look in to the quota details I can see mail api calls there. If I look at the logs there are no errors (but I can't see and of my logs in there...).
It seems odd that I have essentially been charged for sending this (quota used up) but no mails actually got through.
I HAVE checked my spam folder BTW.
It seems that gmail account that you use is a Project Viewer. The docs state that it should be a Developer.
In the end I just used the e-mail address of the currently logged in user - which is always an admin as you can only get to this part of the app if you're an admin.
I could not get it to work using a hardwired address belonging to one of the admins.

SMSLib doesn't receive sms [java edition]

i am trying to use my mobile phone as GSM modem.i use SMSLib for sending and receiving SMS with this modem.
the problem is that when my phone(GSM modem) receive a sms i don't notify with SMSLib.but the code overall is good for example that notifies me when GSM modem receive a call.
my code has not any bug because i only use SMSLib example code for receiving message.
the SMSLib example code is :
public class TestSinaRec
{
public void doIt() throws Exception
{
// Define a list which will hold the read messages.
List<InboundMessage> msgList;
// Create the notification callback method for inbound & status report
// messages.
InboundNotification inboundNotification = new InboundNotification();
// Create the notification callback method for inbound voice calls.
CallNotification callNotification = new CallNotification();
//Create the notification callback method for gateway statuses.
GatewayStatusNotification statusNotification = new GatewayStatusNotification();
OrphanedMessageNotification orphanedMessageNotification = new OrphanedMessageNotification();
try
{
System.out.println("Example: Read messages from a serial gsm modem.");
System.out.println(Library.getLibraryDescription());
System.out.println("Version: " + Library.getLibraryVersion());
// Create the Gateway representing the serial GSM modem.
SerialModemGateway gateway = new SerialModemGateway("modem.com4", "COM4", 115200, "Nokia", " 6303i");
// Set the modem protocol to PDU (alternative is TEXT). PDU is the default, anyway...
gateway.setProtocol(Protocols.PDU);
// Do we want the Gateway to be used for Inbound messages?
gateway.setInbound(true);
// Do we want the Gateway to be used for Outbound messages?
gateway.setOutbound(true);
// Let SMSLib know which is the SIM PIN.
gateway.setSimPin("0444");
// Set up the notification methods.
Service.getInstance().setInboundMessageNotification(inboundNotification);
Service.getInstance().setCallNotification(callNotification);
Service.getInstance().setGatewayStatusNotification(statusNotification);
Service.getInstance().setOrphanedMessageNotification(orphanedMessageNotification);
// Add the Gateway to the Service object.
Service.getInstance().addGateway(gateway);
// Similarly, you may define as many Gateway objects, representing
// various GSM modems, add them in the Service object and control all of them.
// Start! (i.e. connect to all defined Gateways)
Service.getInstance().startService();
// Printout some general information about the modem.
System.out.println();
System.out.println("Modem Information:");
System.out.println(" Manufacturer: " + gateway.getManufacturer());
System.out.println(" Model: " + gateway.getModel());
System.out.println(" Serial No: " + gateway.getSerialNo());
System.out.println(" SIM IMSI: " + gateway.getImsi());
System.out.println(" Signal Level: " + gateway.getSignalLevel() + " dBm");
System.out.println(" Battery Level: " + gateway.getBatteryLevel() + "%");
System.out.println();
// In case you work with encrypted messages, its a good time to declare your keys.
// Create a new AES Key with a known key value.
// Register it in KeyManager in order to keep it active. SMSLib will then automatically
// encrypt / decrypt all messages send to / received from this number.
//Service.getInstance().getKeyManager().registerKey("+306948494037", new AESKey(new SecretKeySpec("0011223344556677".getBytes(), "AES")));
// Read Messages. The reading is done via the Service object and
// affects all Gateway objects defined. This can also be more directed to a specific
// Gateway - look the JavaDocs for information on the Service method calls.
msgList = new ArrayList<InboundMessage>();
Service.getInstance().readMessages(msgList, MessageClasses.ALL);
for (InboundMessage msg : msgList)
System.out.println(msg);
// Sleep now. Emulate real world situation and give a chance to the notifications
// methods to be called in the event of message or voice call reception.
System.out.println("Now Sleeping - Hit <enter> to stop service.");
System.in.read();
System.in.read();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
Service.getInstance().stopService();
}
}
public class InboundNotification implements IInboundMessageNotification
{
public void process(AGateway gateway, MessageTypes msgType, InboundMessage msg)
{
if (msgType == MessageTypes.INBOUND) System.out.println(">>> New Inbound message detected from Gateway: " + gateway.getGatewayId());
else if (msgType == MessageTypes.STATUSREPORT) System.out.println(">>> New Inbound Status Report message detected from Gateway: " + gateway.getGatewayId());
System.out.println(msg);
}
}
public class CallNotification implements ICallNotification
{
public void process(AGateway gateway, String callerId)
{
System.out.println(">>> New call detected from Gateway: " + gateway.getGatewayId() + " : " + callerId);
}
}
public class GatewayStatusNotification implements IGatewayStatusNotification
{
public void process(AGateway gateway, GatewayStatuses oldStatus, GatewayStatuses newStatus)
{
System.out.println(">>> Gateway Status change for " + gateway.getGatewayId() + ", OLD: " + oldStatus + " -> NEW: " + newStatus);
}
}
public class OrphanedMessageNotification implements IOrphanedMessageNotification
{
public boolean process(AGateway gateway, InboundMessage msg)
{
System.out.println(">>> Orphaned message part detected from " + gateway.getGatewayId());
System.out.println(msg);
// Since we are just testing, return FALSE and keep the orphaned message part.
return false;
}
}
public static void main(String args[])
{
TestSinaRec app = new TestSinaRec();
try
{
app.doIt();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
program output is for example :
Gateway Status change for modem.com4, OLD: STOPPED -> NEW: STARTING
Gateway Status change for modem.com4, OLD: STARTING -> NEW: STARTED
Modem Information: Manufacturer: Nokia Model: Nokia 6303i classic
Serial No: 355382041051833 SIM IMSI: ** MASKED ** Signal Level:
-57 dBm Battery Level: 91%
Now Sleeping - Hit to stop service.
New call detected from Gateway: modem.com4 : +989111007483
New call detected from Gateway: modem.com4 : +989111007483
when i searched for this issue i found this :
The correct operation of this method depends on the unsolicited modem
indications and on the correct operation of the CNMI command. If you
see that you are failing to receive messages using a callback method,
probably the modem indications have not been setup correctly.
so i changed my phone(my GSM modem) with Nokia 6303i rather than Nokia 5200 that i used first but the problem didn't solve.
so now i really don't know the problem will solve with choosing another phones ?! or i should search for a better and more reasonable solution.
thank you for any bit of help for solving this problem.
Well the only thing I can think of is that you're starting the Service and then sending the SMS to the modem. Because of this, this line won't be called: Service.getInstance().readMessages(msgList, MessageClasses.ALL);. However, you should still get the notification that a new message has arrived at the modem.
Try implementing the InboundNotification to fetch the messages when it senses any new messages on the modem. Do this by overriding the process() method.
However, it might also be due to the fact that you're actually pressing <Enter> too soon. As the comment say; you have to wait go give the notifications method a chance to be called.
Sometimes it's just something as silly as that. Let me know if any of it helped or if I completely misunderstood your problem. I'm working on a multi-modem gateway myself, so I'd be happy to help.
i had an issue with a GT-I9000 he received the inbound alert but couldn't fetch it the right sms object, i think this is a matter of the Storage Location,
i tried with another phone (Samsung GT-S5670 Android) of a friend of mine who had some messages stored on the SIM Card Memory, the smslibrary was notified and the ReadMessages Class logged all the messages.
so i think you need to find somehow to change storage location on the ReadMessages.java or find an compatible phone that can stores the sms to Sim Card instead of the phone memory.
hope this help.
The problem was with my phone.Smslib doesn't work in listening sms for a variety of phones(including smartphones,most of Nokia phones,etc.).I didn't check but probably this problem will be solved if you use a dedicated GSM modem(like huawei GSM modems)

Facebook login plugin with server side access to users data

I have got few things to work e.g. Using -
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
I am able to get all the details of the user, name, User ID etc.
My Problem is how to take all this information to the server "safely". I don't want this information to be sniffed on its way to server. I use JAVA(Servet/JSP) language, PLEASE HELP ME ON THIS. I wish there was some way like registration plugin where Facebook sends all the information on a redirect_url link.
Regards,
Jagpreet Singh
EDIT: If anybody requires the Java Code -
// it is important to enable url-safe mode for Base64 encoder
Base64 base64 = new Base64(true);
// split request into signature and data
String[] signedRequest = request.getParameter("signed_request").split("\\.", 2);
logger.info("Received signed_request = " + Arrays.toString(signedRequest));
// parse signature
String sig = new String(base64.decode(signedRequest[0].getBytes("UTF-8")));
// parse data and convert to JSON object
JSONObject data = (JSONObject) JSONSerializer.toJSON(new String(base64.decode(signedRequest[1].getBytes("UTF-8"))));
logger.warn("JSON Value = " + data);
// check signature algorithm
if (!"HMAC-SHA256".equals(data.getString("algorithm"))) {
// unknown algorithm is used
logger.error("HMAC-SHA256 Algo? = false, returning ERROR");
return ERROR;
} else {
logger.error("HMAC-SHA256 Algo? = true, Checking if data is signed correctly...");
}
// check if data is signed correctly
if (!hmacSHA256(signedRequest[1], fbSecretKey).equals(sig)) {
// signature is not correct, possibly the data was tampered with
logger.warn("DATA signed correctly? = false, returning ERROR");
return ERROR;
} else {
logger.warn("DATA signed correctly? = true, checking if user has authorized the APP...");
}
// check if user authorized the APP (FACEBOOK User)
if (!data.has("user_id") || !data.has("oauth_token")) {
// this is guest, create authorization url that will be passed
// to javascript
// note that redirect_uri (page the user will be forwarded to
// after authorization) is set to fbCanvasUrl
logger.warn("User has authorized the APP? = false, returning ERROR");
return ERROR;
} else {
logger.warn("User has authorized the APP? = true, Performing User Registration...");
// this is authorized user, get their info from Graph API using
// received access token
// String accessToken = data.getString("oauth_token");
// FacebookClient facebookClient = new
// DefaultFacebookClient(accessToken);
// User user = facebookClient.fetchObject("me", User.class);
}
Facebook sends a signed_request parameter when you authenticate with a client-side method. You can pass this to your server, authenticate it, and then unpack it to get at the information you need. It is encrypted with your app secret, so you can be sure that it is secure.
See the signed_request documentation for more information.

Someone knows a mail (SMTP) delivery library for Java?

I'd like to send mail without bothering with the SMTP-Server which is used for delivery.
So JavaMail API doesn't work for me because I have to specify a SMTP server to connect to.
I'd like the library to find out on its own which SMTP server is responsible for which email address by querying the MX record of the mail address domain.
I'm looking for something like Aspirin. Unfortunately I can't use Aspirin itself because the development stopped 2004 and the library fails to communicate with modern spam hardened servers correctly.
An embeddable version of James would do the task. But I haven't found documentation concerning whether this is possible.
Or does anyone know about other libraries I could use?
One possible solution: get the MX record on your own and use JavaMail API.
You can get the MX record using the dnsjava project:
Maven2 dependency:
<dependency>
<groupId>dnsjava</groupId>
<artifactId>dnsjava</artifactId>
<version>2.0.1</version>
</dependency>
Method for MX record retrieval:
public static String getMXRecordsForEmailAddress(String eMailAddress) {
String returnValue = null;
try {
String hostName = getHostNameFromEmailAddress(eMailAddress);
Record[] records = new Lookup(hostName, Type.MX).run();
if (records == null) { throw new RuntimeException("No MX records found for domain " + hostName + "."); }
if (log.isTraceEnabled()) {
// log found entries for debugging purposes
for (int i = 0; i < records.length; i++) {
MXRecord mx = (MXRecord) records[i];
String targetString = mx.getTarget().toString();
log.trace("MX-Record for '" + hostName + "':" + targetString);
}
}
// return first entry (not the best solution)
if (records.length > 0) {
MXRecord mx = (MXRecord) records[0];
returnValue = mx.getTarget().toString();
}
} catch (TextParseException e) {
throw new RuntimeException(e);
}
if (log.isTraceEnabled()) {
log.trace("Using: " + returnValue);
}
return returnValue;
}
private static String getHostNameFromEmailAddress(String mailAddress) throws TextParseException {
String parts[] = mailAddress.split("#");
if (parts.length != 2) throw new TextParseException("Cannot parse E-Mail-Address: '" + mailAddress + "'");
return parts[1];
}
Sending mail via JavaMail code:
public static void sendMail(String toAddress, String fromAddress, String subject, String body) throws AddressException, MessagingException {
String smtpServer = getMXRecordsForEmailAddress(toAddress);
// create session
Properties props = new Properties();
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props);
// create message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromAddress));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
msg.setSubject(subject);
msg.setText(body);
// send message
Transport.send(msg);
}
This is completely the wrong way to handle this.
Anyone connected to the internet will have some kind of "legit" SMTP server available to them to take the submission of email -- your ISP, your office, etc.
You WANT to leverage because they do several things for you.
1) they take your message and the responsibility to handle that message. After you drop it off, it's not your problem anymore.
2) Any mail de-spamming technologies are handled by the server. Even better, when/if those technologies change (Domain keys anyone?), the server handles it, not your code.
3) You, as a client of that sending mail system, already have whatever credentials you need to talk to that server. Main SMTP servers are locked down via authentication, IP range, etc.
4) You're not reinventing the wheel. Leverage the infrastructure you have. Are you writing an application or a mail server? Setting up mail server is an every day task that is typically simple to do. All of those casual "dumb" users on the internet have managed to get email set up.
Don't.
Sending email is much more complex than it seems. Email servers excel at (or should excel at) reliable delivery.
Set up a separate email server if you need to- that will be essentially the same as implementing one in Java (I doubt you will find libraries for this task- they would be essentially complete mail servers), but much more simpler.

Categories

Resources