Using EWS to send mail from exchange server - android

I followed this link to generate the jar file. I added this to my project. Then have a simple code to send a mail:
public void mailSend() {
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials(
"email", "$*pass!");
service.setCredentials(credentials);
String host = "host";
try {
service.setUrl(new java.net.URI("https://" + host
+ "/EWS/Exchange.asmx"));
service.setTraceEnabled(true);
EmailMessage msg = new EmailMessage(service);
msg.setSubject("Hello world!");
msg.setBody(MessageBody
.getMessageBodyFromText("Sent using the EWS Managed API."));
msg.getToRecipients().add("email");
msg.send();
Log.i("Msg","SEND ");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The problem is that it shows the jar file has no source attachment. Hence I get the error no definition found for class ExchangeService. This should be part of the jar file generated. While exporting as jar file, I had made sure the src folder is clicked.

Related

Telegram API authentication and documentation

I am new in android. I want to use telegram API to develop my own telegram application. There are two problems. 1) I can not find any code sample or documentation or tutorial. I have searched a lot and I have study telegram documentation here. .2) I have used following code to authenticate in telegram. But it does not work. why? code has copied from here.
TelegramApi api = new TelegramApi(new MemoryApiState(false), new appInfo(12345,"Sony","are these values important?","1","en"), new apiCallback());
// Create request
String phoneNumber = "98123456789";
TLRequestAuthCheckPhone checkPhone = new TLRequestAuthCheckPhone(phoneNumber);
// Call service synchronously
TLCheckedPhone checkedPhone = null;
try {
Log.d("meme", "----");
checkedPhone = api.doRpcCall(checkPhone);
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("meme", "IOException");
}

Send XML file to FTP/HTTPS server

I create small tracking app which get coordinates write them to xml file and then send this file with that data to ftp server. I am using function "SendFileGPS" to send that file but apk all the time crashes and it doesn't work. This function is using additional library common net 1.4 and it is quite strange because all the time when I start Android Studio I must download this library from web by Android Studio. And I got some additional questions.
I was thinking that maybe not only this function is a problem, how should look this server I mean how proper this server to get file from this app?
There is a another way to send this file without using additional libs ?
How it should look if I want send this file to another type of server (HTTPS)?
public void SendFileGPS()
{
FTPClient mFTP = new FTPClient();
try {
// Connect to FTP Server
mFTP.connect("here I put adress IP");
mFTP.login("here I put login", "here I put pass");
mFTP.setFileType(FTP.BINARY_FILE_TYPE);
mFTP.enterLocalPassiveMode();
// Prepare file to be uploaded to FTP Server
File file = new File("/path/to/MyXmlFileName.xml");
FileInputStream ifile = new FileInputStream(file);
// Upload file to FTP Server
mFTP.storeFile("filetotranfer",ifile);
mFTP.disconnect();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Android FTP server authenticates once

I am trying to implement an FTP server in my application using the Apache FTP server library.
The server is up and running and working fine, but only once.
Note: I am using a hardcoded user for now. username: test and password: test
So in order:
App is launched, server is started, lets all FTP clients login.
App is killed by user.
App is started by user and server is started. Replies 530 authentication failed to user logging in with username: test and password: test
After that it responds with 530 authentication failed
My code below for making the server:
public void makePropertiesFile(){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/user.properties");
if(file.exists() == false){
try {
file.createNewFile();
logMessage("user.properties File did not exist, made one");
properties = file;
this.addUsers();
} catch (IOException e) {
e.printStackTrace();
}
}
else {
logMessage("File already exists, no need to recreate");
userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(properties);
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
org.apache.ftpserver.ftplet.UserManager userManager = userManagerFactory.createUserManager();
serverFactory.setUserManager(userManager);
}
}
public void addUsers(){
userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(properties);
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
baseUser = new BaseUser();
baseUser.setName("test");
baseUser.setPassword("test");
baseUser.setHomeDirectory(Environment.getExternalStorageDirectory().getAbsolutePath());
baseUser.setEnabled(true);
List<Authority> authorities = new ArrayList<Authority>();
authorities.add(new WritePermission());
baseUser.setAuthorities(authorities);
org.apache.ftpserver.ftplet.UserManager userManager = userManagerFactory.createUserManager();
try {
userManager.save(baseUser);
} catch (FtpException e) {
e.printStackTrace();
logMessage("Could not save User");
}
serverFactory.setUserManager(userManager);
}
public void start(){
serverFactory = new FtpServerFactory();
listenerFactory = new ListenerFactory();
listenerFactory.setPort(port);
serverFactory.addListener("default",listenerFactory.createListener());
ftpServer = serverFactory.createServer();
this.makePropertiesFile();
try {
ftpServer.start();
logMessage("Started FTP server on port: " + port);
} catch (FtpException e) {
e.printStackTrace();
logMessage("Failed to start FTP server on port: " + port);
}
}
see this link http://androidexample.com/FTP_File_Upload_From_Sdcard_to_server/index.php?view=article_discription&aid=98&aaid=120
has a working project FTP with Android app

Upload file with Azure Storage using SAS (Shared Access Signature)

I know that there is library available for uploading the file using Azure Storage. I have refer this for same.
But, they have not give information for how to use SAS with that. I have account name, and sas url for access and upload file there. But I don't know how to use that for uploading file.
If I use above mention library it shows me invalid storage connection string because I am not passing the key in it (Which is not required with sas). So I am confused how I can upload file.
I have refer this documentation also for uploading file using sas. but not getting proper steps to do this. They have made demo for their windows app. I want to have that in android with use of sas.
Update
I have try with below code with reference to the console app made by Azure to check and access SAS.
try {
//Try performing container operations with the SAS provided.
//Return a reference to the container using the SAS URI.
//CloudBlockBlob blob = new CloudBlockBlob(new StorageUri(new URI(sas)));
String[] str = userId.split(":");
String blobUri = "https://myStorageAccountName.blob.core.windows.net/image/" + str[1] + "/story/" + storyId + "/image1.jpg" + sas.toString().replaceAll("\"","");
Log.d(TAG,"Result:: blobUrl 1 : "+blobUri);
CloudBlobContainer container = new CloudBlobContainer(new URI(blobUri));
Log.d(TAG,"Result:: blobUrl 2 : "+blobUri);
CloudBlockBlob blob = container.getBlockBlobReference("image1.jpg");
String filePath = postData.get(0).getUrl().toString();
/*File source = new File(getRealPathFromURI(getApplicationContext(),Uri.parse(filePath))); // File path
blob.upload(new FileInputStream(source), source.length());*/
Log.d(TAG,"Result:: blobUrl 3 : "+blobUri);
//blob.upload(new FileInputStream(source), source.length());
//blob.uploadText("Hello this is testing..."); // Upload text file
Log.d(TAG, "Result:: blobUrl 4 : " + blobUri);
Log.d(TAG, "Write operation succeeded for SAS " + sas);
response = "success";
//Console.WriteLine();
} catch (StorageException e) {
Log.d(TAG, "Write operation failed for SAS " + sas);
Log.d(TAG, "Additional error information: " + e.getMessage());
response = e.getMessage();
} catch (FileNotFoundException e) {
e.printStackTrace();
response = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
response = e.getMessage();
} catch (URISyntaxException e) {
e.printStackTrace();
response = e.getMessage();
} catch (Exception e){
e.printStackTrace();
response = e.getMessage();
}
Now, when I upload text only it says me below error
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
Now, my requirement is to upload Image file. So when I uncomment code for uploading image file it is not giving me any error but even not uploading image file.
#kumar kundal
The mechanism that you have explained is completely right.
Below is the more detailed answer about uploading profile image to the Azure Server.
First create SAS url to upload Image(or any file) to blob storage:
String sasUrl = "";
// mClient is the MobileServiceClient
ListenableFuture<JsonElement> result = mClient.invokeApi(SOME_URL_CREATED_TO_MAKE_SAS, null, "GET", null);
Futures.addCallback(result, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(JsonElement result) {
// here you will get SAS url from server
sasUrl = result; // You need to parse it as per your response
}
#Override
public void onFailure(Throwable t) {
}
});
Now, you have sasURL with you. That will be something like the below string:
sv=2015-04-05&ss=bf&srt=s&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=F%6GRVAZ5Cdj2Pw4tgU7IlSTkWgn7bUkkAg8P6HESXwmf%4B
Now, you need to append the sas url with your uploading url. See below code in which I have appended the SAS url with my uploading request.
try {
File source = new File(filePath); // File path
String extantion = source.getAbsolutePath().substring(source.getAbsolutePath().lastIndexOf("."));
// create unique number to identify the image/file.
// you can also specify some name to image/file
String uniqueID = "image_"+ UUID.randomUUID().toString().replace("-", "")+extantion;
String blobUri = MY_URL_TO_UPLOAD_PROFILE_IMAGE + sas.replaceAll("\"","");
StorageUri storage = new StorageUri(URI.create(blobUri));
CloudBlobClient blobCLient = new CloudBlobClient(storage);
CloudBlobContainer container = blobCLient.getContainerReference("");
CloudBlockBlob blob = container.getBlockBlobReference(uniqueID);
BlobOutputStream blobOutputStream = blob.openOutputStream();
byte[] buffer = fileToByteConverter(source);
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
int next = inputStream.read();
while (next != -1) {
blobOutputStream.write(next);
next = inputStream.read();
}
blobOutputStream.close();
// YOUR IMAGE/FILE GET UPLOADED HERE
// IF YOU HAVE FOLLOW DOCUMENT, YOU WILL RECEIVE IMAGE/FILE URL HERE
} catch (StorageException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
I hope this information help you lot for uploading the file using blob storage.
Please let me know if you have any doubt apart from this. I can help in that.
Uploading a pic to BLOB storage . I got it after searching for hours .Take a look :-
Uploading the photo image is a multistep process:
First you take a photo, and insert a TodoItem row into the SQL database that contains new meta-data fields used by Azure Storage.
A new mobile service SQL insert script asks Azure Storage for a Shared Access Signature (SAS).
That script returns the SAS and a URI for the blob to the client.
The client uploads the photo, using the SAS and blob URI.
So what is a SAS?
It's not safe to store the credentials needed to upload data to the Azure Storage service inside your client app. Instead, you store these credentials in your mobile service and use them to generate a Shared Access Signature (SAS) that grants permission to upload a new image. The SAS, a credential with a 5 minute expiration, is returned securely by Mobile Services to the client app. The app then uses this temporary credential to upload the image.
for further queries and detail analysis. Visit this official documentation https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-upload-data-blob-storage/

Can't receive mails with Pop in Android

I can receive my mails with Imap with this code sample :
URLName server = new URLName("imaps://" + username + ":"+ password + "#imap.gmail.com/INBOX");
Session session = Session.getDefaultInstance(new Properties(), null);
Folder folder = session.getFolder(server);
if (folder == null)
{
System.exit(0);
}
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
But sometimes Imap doesn't give any service and at those times I want to use Pop but I couldn't use it with my code. It is different the other codes for using receive mail. But in Android only this code is working.
What should I change in this code to work with Pop?
First, there's a nice URLName constructor that takes all the component pieces as separate parameters, so you don't have to do string concatenation.
Switch from IMAP to POP3 requires changing the protocol name as well as the host name. See the JavaMail FAQ for examples. The protocol name is "pop3s" and the host name is "pop.gmail.com".
Finally, you should use Session.getInstance instead of Session.getDefaultInstance. Compare the javadocs for the two methods to understand why.
How about this one.Really worked for me!!(Source:here)
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
URLName url = new URLName("pop3", "pop.gmail.com", 995, "","youremailid#gmail.com",yourpassword);
Session session = Session.getInstance(pop3Props, null);
Store store = new POP3SSLStore(session, url);
try {
store.connect();
} catch (MessagingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Folder folder = null;
try {
folder = store.getDefaultFolder();
folder = folder.getFolder("INBOX");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (folder == null) {
System.exit(0);
}
try {
folder.open(Folder.READ_ONLY);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try retreiving folder via store object.And also mention that the folder you wish to retreive is INBOX!Also note that in settings,port number is 995 form pop.(You may leave the first six lines as they are.)

Categories

Resources