Attachment to Email Java - java

I have written a code in order to be able to launch the default email service provider which is outlook for me. this is the code i have:
if(role.getValue().equals("1")) {
Desktop desktop = Desktop.getDesktop();
String message = "mailto:username#domain.com?subject=New_Profile&body=NewProfile";
try {
desktop.mail(uri);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am trying to attach something to the email automatically but its not working. Instead, will it be possibly to retrieve some data from input fields in my program and automatically add that data as body to the email?
I tried embedding a statement somehow, but its not working. could someone please advise?
Desktop desktop = Desktop.getDesktop();
String message = "mailto:username#domain.com?subject=New_Profile&body=person.getPdfName()";
Why would the code above not do anything? Is person.getPdfName() misplaced?

Have a look at these answers, not sure any of them solve your problem, but they do give a decent description of why its not that simple. Not all email clients support attachments in this way.
Start Mail-Client with Attachment?
How to open an email client and automatically attach file in java
http://forums.devshed.com/windows-help-34/defaut-mail-client-with-attachment-on-xp-71305.html

Java has an API that is able to send messages and perform all the necessary functions, such as attach files. Check the class MimeMessage to help you.
In your case, I believe that the body of your message would become a simple text containing the name of the PDF, isn't that so?

Related

Calling Windows COM interface and get Response

I have a system that has Windows COM interface so that external applications can connect to it and it has following details
Interface: InterfaceName
Flags: (1234) Dual OleAutomation Dispatchable
GUID: {ABCDEFG-ABCD-1234-ABCD-ABCDE1234}
I'd like to connect to this interface through Java Spring Application, it will sends a request to this interface and process the response.
I've tried to use the following code
ActiveXComponent mf = new ActiveXComponent("ApplicationName.InterfaceName");
try {
Dispatch f2 = mf.QueryInterface(" {ABCDEFG-ABCD-1234-ABCD-ABCDE1234} ");
Dispatch.put(f2, 201, new Variant("Request String"));
} catch (Exception e) {
e.printStackTrace();
}
The executable file opens but it doesn't do what I want. I want to do the following.
How do I make sure, my interface has bee registered, I can see it
under
Computer\HKEY_CLASSES_ROOT\ApplicationName.InterfaceName
Using ActiveXComponent opens the instance of application, which is not required. Application is already running.
call the interface with dispid.
Retreive the response from the call/put/invoke ( which suits best
for my requiremet ? ) and process the response.
I'm working first time with JAVA-COM_Interface and don't have much experience with it also I could find very few examples on the internet for it and I tried to convert the example I found for my project, also I am not sure the approach I am taking to call the interface is correct or not I would be glad if you can give a hand!
I have resolved this using JACOB lib.
1) Download JACOB folder from here.
2) Check your application is working & has details under
Computer\HKEY_CLASSES_ROOT\ApplicationName.InterfaceName
3) Make sure ApplicationName.dll file is registered. If not use this link for more info
regsvr32
4) Use this Java Code to send data to COM Interface with below simple code.
Dispatch dispatch = new Dispatch("Application.InterfaceName");
Variant response = Dispatch.call(dispatch, <DISPID>, message);
syso(response.getString()); // to print the response
Hope this helps.

How to prepare (not send) an e-mail in outlook, with java? [duplicate]

This question already has an answer here:
Need to open ms outlook with attachments [duplicate]
(1 answer)
Closed 5 years ago.
I'm trying to write a program that, after the user reviews certain equipment and answers some questions about them, it creates a report and automatically sends it to a database.
The program itself is not very complicated, I have it more or less solved, but I fail in the part of sending the mail. I have been searching, and I have found the JavaMail API, and I have even learned to send emails with it, more or less, but my company blocks any attempt of an external program to send e-mail, so I have decided to give it a different approach and try that instead of sending it automatically, prepare the mail in the Outlook editor itself, ready to be sent, and that the user only has to click to send, after reviewing it.
But looking here, or Javamail documentation, or even googling, I can't find any reference to people doing it, even knowing that it can be done, as I've been using some programs that do this by themselves!
So, the question is: can I do this with JavaMail? If yes, could you provide me with an example, or something, to learn how to use it? If not, any other libraries able to do that?
Maybe this is a simple question, maybe Java itself has a function for doing it. But I've been looking for it for a week, and I can't find anything that I can use.
I'm very very new to programming (a bit more than a year), so try to keep the answer to a basic level that some novice can understand, please.
As an example, let's say I have an equipment called X. The programs asks me "Does X makes excessive noise?" and I check "Correct" button. Then, it asks "Has X a normal pressure level?", and I check "Incorrect" button, and add a comment "Pressure level to high". And so on, until I've answered every question. Then, when I have finished with X equipment, and push the "Finish" button, I want a "New Email" outlook window to pop out, with the receiver already fulfilled, "Equipment X 27/12/2017 morning revision" as subject, and the body something like:
"Noise revision: correct
Pressure level: incorrect Comment: Pressure level to high
Question 3: correct
Question 4: correct
etc."
I've solved already how to create the body, and assign every parameter to its place. The problem is the pop out and auto fulfilling thing, how to export all that data to outlook to be ready to be sent. And yes, bosses specify that I have to use outlook.
So I would propose to create and save a message with JavaMail as discussed here
Now, you cannot send the particular message right away because the message header does not contain the following line:
"X-Unsent":1
(which will actually instruct the outlook client that the message is in draft state)
So the code should look something like this:
(note that this is not tested, just copy pasted from different sources)
public static void createMessage(String to, String from, String subject, String body, List<File> attachments) {
try {
Message message = new MimeMessage(Session.getInstance(System.getProperties()));
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
//make it a draft!!
message.setHeader("X-Unsent", "1");
// create the message part
MimeBodyPart content = new MimeBodyPart();
// fill message
content.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(content);
// add attachments
for(File file : attachments) {
MimeBodyPart attachment = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachment.setDataHandler(new DataHandler(source));
attachment.setFileName(file.getName());
multipart.addBodyPart(attachment);
}
// integration
message.setContent(multipart);
// store file
message.writeTo(new FileOutputStream(new File("c:/mail.eml")));
} catch (MessagingException ex) {
Logger.getLogger(Mailkit.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Mailkit.class.getName()).log(Level.SEVERE, null, ex);
}
}
Hope this helps.

How can we develop a test method in Java (& Selenium Webdriver), for tracking 'a reset e-mail Notification', without verifying in mailbox?

I am developing UI Automation for testing a web app and currently confronted with, writing a test method to track if an email notification has been sent to a recipient. BUT, the challenge here is NOT to wait for some time and then checking in the recipient's mail box, but to be able to track the outgoing request for verification on the Web App itself.
Here is my current Code checking if mail URL is there or not after triggering the email notification.:
#Test
public void chkEmailNotif() {
try {
PO.clickEmailUrl(); //PO is a page object class
assertTrue(PO.MailFrameSeen());
PO.clickYes();
System.out.println(" Clicked on Yes button of the Mail frame Box ");
assertFalse(!PO.isMailurlSeen());
} catch (Exception e) {
System.out.println ("Catched exception e" + e )
}
}
Any suggestions are welcome.
Thanks in advance.
Mock the mailbox and check the message is sent. Set the configuration to use the mock or the real mailbox in a file that changes with the environment.

How to control the handset using AT commands in java

I know that by using AT commands we can control the handset.As example unlocking screen we can give a specific AT command or moving right to the menu or left or bottom or up we can give specific AT commands. What all are the AT commands for doing this kind of control.
Thank you.
From what I understand, the AT commands are more used for phone-type functions (making calls, or sending SMS, etc), rather than menu navigation, etc.
I'm not entirely sure if that was your end-goal after menu navigation, but you can find more details here: http://en.wikipedia.org/wiki/Hayes_command_set (the original +AT command set)
If you wanted to send SMS from a handset connected to your computer you might want to take a peek at this page: http://www.developershome.com/sms/atCommandsIntro.asp
If you wanted more control when performing functions, like sending SMS, etc, you might want to investigate "PDU Mode."
It is entirely possible that some handset manufacturers may have implemented additional +AT commands to allow other functions to be performed, so you might do better by specifically searching for the commands related to the handset you are using.
(Of course, if you're having issues connecting to the handset hardware itself, you need to ensure you have either the javax.comm extension or some favoured Java USB API installed)
If post doesn't help, perhaps you could provide more details in your question? (eg. what you are ultimately trying to do, if you think it would help)
List of AT commands
sample java code to use AT command
public void servicesDiscovered(int transID, ServiceRecord serviceRecord[])
{
String url = serviceRecord[0].getConnectionURL(1, false);
try
{
//ClientSession conn= (ClientSession)Connector.open(url);
StreamConnection meineVerbindung = (StreamConnection) Connector.open(url);
if(conn== null)
System.out.println("Kann Service URL nicht oeffnen\n");
else
{
OutputStream out = conn.openOutputStream();
InputStream in = conn.openInputStream();
String message = "AT+CGMI\r\n";
// send AT-command
System.out.println("send AT Comand request: "+message);
out.write(message.getBytes());
out.flush();
out.close();
byte buffer[] = new byte[10000];
// read the response from mobile phone
in.read(buffer);
System.out.println("AT Comand response: "+buffer.toString());}
}
catch(IOException e)
{
System.out.println("Service Error(3): "+e.getMessage());
}
}

How do I programatically list my LinkedIn contacts?

I have searched the LinkedIn APIs, but I cannot see a way to get the contacts. I know that there are some applications that have this functionality, but I am wondering is this legal or if they use some kind of partner API?
I think that the Connections API probably does what you need.
This is a Web API, so from Java you would need to use an URL.connect() or Apache HttpClient or something like that, using an appropriately formed request URL. Then you'd need to configure an XML parser to parse the XML response body and extract the contact details.
As the page states, your client needs to be authenticated (as you) to access your contacts, and the API won't let you see details that you cannot see using your web browser.
I created a plugin for Play Framework to easily integrated with LinkedIn's OAuth: http://geeks.aretotally.in/projects/play-framework-linkedin-module.
Hopefully it can help. You should def check out Play, very very cool Java framework.
1) First click below link and add your app to developer account
The r_network scope recently changed to be a LinkedIn partner-only permission. You can apply for access to their partnership program here:
https://developer.linkedin.com/partner-programs/apply
2) After successfully creation of your app on developer account make permission of r_network
3) Insert Following code after importing all required linked-in sdk file from this https://developer.linkedin.com/docs/android-sdk
private static final String topCardUrl = "https://api.linkedin.com/v1/people/~:(id,first-name,email-address,last-name,num-connections,headline,picture-url,industry,summary,specialties,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes),associations,interests,num-recommenders,date-of-birth,publications:(id,title,publisher:(name),authors:(id,name),date,url,summary),patents:(id,title,summary,number,status:(id,name),office:(name),inventors:(id,name),date,url),languages:(id,language:(name),proficiency:(level,name)),skills:(id,skill:(name)),certifications:(id,name,authority:(name),number,start-date,end-date),courses:(id,name,number),recommendations-received:(id,recommendation-type,recommendation-text,recommender),honors-awards,three-current-positions,three-past-positions,volunteer)?format=json";
public void getUserData() {
APIHelper apiHelper = APIHelper.getInstance(MainActivity.this);
apiHelper.getRequest(MainActivity.this, topCardUrl, new ApiListener() {
#Override
public void onApiSuccess(ApiResponse result) {
try {
//here you get data in json format
//you have to parse it and bind with adapter for connection list
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onApiError(LIApiError error) {
}
});
}

Categories

Resources