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);
Related
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
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);
}
I'm trying to send an email with an attachment. The whole thing works fine, except for the part that the attachment sent sends the attached file with no extension.
For example, sending File.rar will receive file
This is how I'm doing it:
public class EmailSender {
public static void main(String[] args) {
String TO = "Receiver#yahoo.com";
String host = "smtp.gmail.com";
String port = "465";
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties mailConfig = new Properties();
mailConfig.put("mail.smtp.host", host);
mailConfig.put("mail.smtp.socketFactory.port", port);
mailConfig.put("mail.smtp.socketFactory.class", SSL_FACTORY);
mailConfig.put("mail.smtp.auth", "true");
mailConfig.put("mail.smtp.port", port);
Session session = Session.getDefaultInstance(mailConfig,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("Username", "Password");
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#gmail.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
message.setSubject("Email with Attachment SUBJECT");
BodyPart messageBodyTxt = new MimeBodyPart();
messageBodyTxt.setText("Email with Attachment BODY");
MimeBodyPart messageBodyAttachment = new MimeBodyPart();
String filePath = "D:\\Unlocker1.9.2.rar";
DataSource source = new FileDataSource(filePath);
messageBodyAttachment.setDataHandler(new DataHandler(source));
messageBodyAttachment.setFileName("Unlocker1.9.2" + ".rar");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyTxt);
multipart.addBodyPart(messageBodyAttachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Email sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Using the advice from the comment, the proper method would be setDisposition and you would set it for the MimeBodyPart in question. Therefore, with the code above, one would do:
messageBodyAttachment.setDisposition(javax.mail.Part.ATTACHMENT);
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);
}
}
}
}
I wanted the mail to be sent automatically at a specific time. I am able to send a mail but I can't make it to be done automatically . Can anyone please tell me how to send automatically? These below are my codes for sending a mail:
public class SendEmail {
String d_email = "sofien.fkih#gmail.com",
d_password = "",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "sofien.fkih#gmail.com",
m_subject = "Testing",
m_text = "Hey, this is the testing email.";
// Those are the values that have the email information
public void send(String from, String pass, String host, String port, String to, String subject, String text) {
Properties props = new Properties();
// Read properties file.
props.put("mail.smtp.user", from);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(d_email, d_password);
}
}
}
Check out java.util.Timer and if it is not enough for you read about Quartz - the pure java cron compatible scheduler.
Quartz seems better option.This tutorial might help you to set up quartz.
try
public class SendEmail extends TimerTask{
public static void main(String[] args){
Timer t = new Timer();
t.schedule(new SendEmail(), 0, 9000); //send email every 9 seconds
}
#Override
public void run() {
// TODO Auto-generated method stub
//Your email syntax here
}
}