How to write a mail application with java mail API that run all time at glassfish server and search a specific time in the database and send mail at that time. i have web application written in JSF that need to send mail at specific time given in database.
For gmail, use below code
import org.apache.commons.mail.*;
public class GmailEmailWorking {
public static void main(String[] args) {
String myEmailId = "xyz#gmail.com";
String myPassword = "password";
String senderId = "xyz#yahoo.com";
try {
MultiPartEmail email = new MultiPartEmail();
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator(myEmailId, myPassword));
email.setDebug(true);
email.setHostName("smtp.gmail.com");
email.setFrom(myEmailId);
email.setSubject("Hi");
email.setMsg("This is a test mail ... :-)\n\nPlease check attachements that I have sent.\n\nThanks,\nFahim");
email.addTo(senderId);
email.setTLS(true);
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("/Users/fahadparkar/Desktop/Fahim/tables.xlsx");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Excel");
attachment.setName("tables.xlsx");
email.attach(attachment);
email.send();
System.out.println("Mail sent!");
} catch (Exception e) {
System.out.println("Exception :: " + e);
}
}
}
Below are list of jar files you will need
commons-email-1.2.jar
activation.jar
mail.jar
To send from other server, you will need to do changes at below line
email.setSmtpPort(587);
email.setHostName("smtp.gmail.com");
Related
I try to mock server with mailbox to test mail send by another apllication.
I try to use GreenMail. I want to my test received mail send from some apllication.
This is my code in test:` ServerSetup setup = new ServerSetup(3025, "localhost", "smtp");
GreenMail greenMail = new GreenMail(setup);
greenMail.setUser("user1#mail.com", "user1", "user1");
greenMail.start();
greenMail.waitForIncomingEmail(50000, 1);
Message[] messages = greenMail.getReceivedMessages();
try {
System.out.println(messages[0].getSubject());
} catch (MessagingException e) {
e.printStackTrace();
}
}`
I run this code and send mail from my personal mailbox to adress "user1#mail.com". And mail doesn't reaches. Sombody know what I do wrong ?Please for help. Maybe i should use another tool for what I want achieve ?
I want to test my Emil Com server and SMTP capacity. So i need to send mail to different Email account from my Application. But i cant not create 10000 mail iD's each time. IS there any simulation tool available to send a Email from my application without creating the Mail id's (Gmail, yahoo etc)
Use this method emailNotification() and implement as per your need. Concatinate all the email_id with a comma seprator abc#abc.com,abc1#abc.com,abc2#abc.com and pass the string to the v_sBCC.
This function might help you out. Thanks..
private void emailNotification(){
String v_sTo;
String v_sFrom;
String v_sBCC = "abc#gmail.com,abc1#gmail.com" //add a number of emails with a Comma separator.
DataSource v_objSource;
Properties v_objProperties;
Session v_objSession;
MimeMessage v_sMessage;
BodyPart v_objMessageBodyPart;
Multipart v_objMultipart;
try {
v_sFrom = "Set From Name To Show User that From which Email you received Mail";
v_objProperties = new Properties();
v_objProperties.put("mail.smtp.host", smtp.google.com);
v_objProperties.put("mail.smtp.auth", "true");
v_objProperties.put("mail.debug", "false");
v_objProperties.put("mail.smtp.port", 25);
v_objProperties.put("mail.smtp.socketFactory.port", 25);
v_objProperties.put("mail.smtp.starttls.enable", "true");
v_objProperties.put("mail.transport.protocol", "smtp");
v_objSession = Session.getInstance(v_objProperties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("gmail.id", "password");
}
});
v_sMessage = new MimeMessage(v_objSession);
v_sMessage.setFrom(new InternetAddress(v_sFrom, "Your Company Name"));
v_sMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(v_sTo));
v_sMessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(v_sBCC));
v_sMessage.setSubject("Set Your Own Subject");
v_sMessage.setText("Set Your Own Body");
Transport.send(v_sMessage);
} catch (MessagingException v_exException) {
v_exException.printStackTrace();
} catch (UnsupportedEncodingException v_exException) {
v_exException.printStackTrace();
}
}
I need to download gmail-> emails into my local system. Idea is to convert each 'email's' content into an XML and upload it onto some other system. I am wondering if there is an API which allows me to download 'my' e-mails from gmail account onto a local hard drive (e.g c:\gmail-mails)
Here is a code snipped I got from this site.
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
//TODO store the message cntent in anXML file
}
} catch (NoSuchProviderException e) {
e.printStackTrace();//...
} catch (MessagingException e) {
e.printStackTrace();//...
}
And maybe better, also have a look at the extention of JavaMail Google made.
I have used java mail API for sending mail in my application using java and web driver.My requirement is to send a mail whenever a link/url is down.Even though mail is send when i give url incorrectly ,but at the same time if a url is not loading due any other issue (page not found), found that mail is not getting send.
public void SendMail(String url,String str)
{
try
{
Sheet mailsheet = w.getSheet("mail");
String from = mailsheet.getCell(0,1).getContents().toString().trim();
String toEmailID=mailsheet.getCell(1,1).getContents().toString().trim();
Properties props = new Properties();
String mailprotocol = mailsheet.getCell(2,1).getContents().toString().trim();
String mailprotocoltype = mailsheet.getCell(3,1).getContents().toString().trim();
String mailhost = mailsheet.getCell(4,1).getContents().toString().trim();
String mailhostip = mailsheet.getCell(5,1).getContents().toString().trim();
String mailport=mailsheet.getCell(6,1).getContents().toString().trim();
String mailportid=mailsheet.getCell(7,1).getContents().toString().trim();
props.put(mailprotocol,mailprotocoltype);
props.put(mailhost,mailhostip);
props.put(mailport,mailportid);
javax.mail.Session mailSession =javax.mail.Session.getInstance(props);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toEmailID));
msg.setSubject("Test Summary");
msg.setContent("<html><body>Dear Admin,<br> Website page "+ "<b><i>"+url + "</b></i>"+" cannot be loaded due to the following :<br> <br></body></html>"+str,"text/html");
Transport.send(msg);
System.out.println("Mail is successfully sent to Recipient address with Error information.");
}
catch(Exception e)
{
//System.out.println(e);
System.out.println("Mail cannot be send to Recipient address due to connection error");
}
}
public void x() {
SendMail(url,driver.getTitle());
}
The answer is probably in the bit of code you don't show us : the part where you test the URL.
The response code for a wrong domain name is different from the response code due to a page not found. Also, depending on the system you're targetting, it's possible that page not found are redirected to the index page, making detection even more difficult.
I am trying to download a file from ftp server using com.enterprisedt.net.ftp.FileTransferClient and the file name is "ABC.DEF.GHI.JKL(0)", This is a mainframe file and it is a valid file name(checked with mainframe admin).
public static void main(String[] args) {
// extract command-line arguments
String host = "111.111.111.111";
String username = "bbbbbbbb";
String password = "cccccccccp";
String filename = "ABC.DEF.GHI.JKL(0)";
// set up logger so that we get some output
Logger log = Logger.getLogger(ConnectToServer.class);
Logger.setLevel(Level.INFO);
FileTransferClient ftp = null;
try {
// create client
log.info("Creating FTP client");
ftp = new FileTransferClient();
// set remote host
log.info("Setting remote host");
ftp.setRemoteHost(host);
ftp.setUserName(username);
ftp.setPassword(password);
// connect to the server
log.info("Connecting to server " + host);
ftp.connect();
log.info("Connected and logged in to server " + host);
//Downloading file from server
log.info("Downloading file");
ftp.downloadFile(filename+".copy", filename);
log.info("File downloaded");
// Shut down client
log.info("Quitting client");
ftp.disconnect();
log.info("Example complete");
} catch (Exception e) {
e.printStackTrace();
}
}
The error i am receiving is :
ERROR [FTPClient] 2 Mar 2012 21:44:08.359 : Caught and rethrowing exception in initGet() : Invalid data set name "ABC.DEF.GHI.JKL(0)". Use MVS Dsname conventions.
com.enterprisedt.net.ftp.FTPException: 501 Invalid data set name "ABC.DEF.GHI.JKL(0)". Use MVS Dsname conventions.
at com.enterprisedt.net.ftp.FTPControlSocket.validateReply(FTPControlSocket.java:1223)
at com.enterprisedt.net.ftp.FTPClient.initGet(FTPClient.java:3109)
at com.enterprisedt.net.ftp.FTPClient.getData(FTPClient.java:3156)
at com.enterprisedt.net.ftp.FTPClient.getFile(FTPClient.java:2970)
at com.enterprisedt.net.ftp.FTPClient.get(FTPClient.java:2356)
at com.enterprisedt.net.ftp.FileTransferClient.downloadFile(FileTransferClient.java:703)
at com.enterprisedt.net.ftp.FileTransferClient.downloadFile(FileTransferClient.java:683)
at com.bluecrossma.ConnectToServer.main(ConnectToServer.java:47)
Please suggest me on how to resolve this problem.
Thanks in Advance
Found the answer in this link: torsas.ca/attachments/File/03012008/FTP_Fileref.pdf Just needed to add single quotes inside the double quotes..Thanks guys.