Save email into sent folder using spring mail - java

I have a function to send email to customer to confirm order which customer has ordered.
Code:
#Bean
public JavaMailSender orderMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("mail.myserver.vn");
mailSender.setPort(25);
mailSender.setUsername(SystemParams.ORDER_EMAIL_ADDRESS);
mailSender.setPassword(SystemParams.ORDER_EMAIL_PASSWORD);
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.store.protocol", "imaps");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.debug", "true");
return mailSender;
}
private void sendEmailConfirm(HttpSession session) {
try {
MimeMessage message = emailSender.createMimeMessage();
boolean multipart = true;
MimeMessageHelper helper = new MimeMessageHelper(message, multipart);
Object object = session.getAttribute(Constants.CART_CONFIRM_ATTRIBUTE_NAME);
String htmlMsg = "<h4>Đơn hàng #" + object + " đã được tạo thành công.<h4>";
message.setContent(htmlMsg, "text/html; charset=utf-8");
message.setSubject("Xác nhận đơn hàng #" + object, StandardCharsets.UTF_8.displayName());
message.setFrom(SystemParams.ORDER_EMAIL_ADDRESS);
helper.setTo("customeremail#gmail.com");
// helper.setSubject();
this.emailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
All data I currently store in session. With this code, email sent successfully but it don't store in sent folder, How can I save sent email to sent folder in email server?

You may need to do it explicitly
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imap");
store.connect(host, "user", "userpwd");
Folder folder = (Folder) store.getFolder("Sent");
if (!folder.exists()) {
folder.create(Folder.HOLDS_MESSAGES);
}
folder.open(Folder.READ_WRITE);
System.out.println("appending...");
try {
folder.appendMessages(new Message[]{message});
// Message[] msgs = folder.getMessages();
message.setFlag(FLAGS.Flag.RECENT, true);
} catch (Exception ignore) {
System.out.println("error processing message " + ignore.getMessage());
} finally {
store.close();
folder.close(false);
}

Related

How to get Bounced mails in java

I am implementing a Bulk mail application, in this applica This link.
I am able to connect to the server and and send the emails to the destination addresses, but I want to identify the undelivered mails.
By using below program I am able to get the email subjects. But based on the subject it will be difficult to identify the exact undelivered mails.
public static void main(String[] args) {
Properties props = System.getProperties();
props.setProperty("mail.host", host);
props.setProperty("mail.user", user);
props.setProperty("mail.from", from);
//props.setProperty("mail.debug", "true");
//props.setProperty("mail.domain", domain);
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore(protocol);
Session session1 = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
System.out.println((store.isConnected())?"Already Connected":"Not Already Connected");
store.connect(host, port, user, password);
Folder inbox = store.getFolder("INBOX");
System.out.println("folder>>>" + inbox.getFullName() + "<<<");
System.out.println("folder URLName>>>" + inbox.getURLName() + "<<<");
System.out.println((inbox.exists()?"folder exists":"folder does not exist"));
int folderType = inbox.getType();
System.out.println("folder type>>>" + folderType + "<<<");
inbox.open(Folder.READ_WRITE);
System.out.println("Message Count:" + inbox.getMessageCount());
Message[] m = inbox.getMessages();
for (int x = 0; x < m.length; x++) {
System.out.println(m[x].getSubject());
}
inbox.close(false);
store.close();
}catch(Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
How can I get the undelivered mails(Bounced).
I am using Hmailserver as my mail server.
You can use this below code
MimeMessage payload = (MimeMessage) message.getPayload();
Multipart mp = (Multipart) payload.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart bodyPart = mp.getBodyPart(i);
StringWriter writer = new StringWriter();
IOUtils.copy(bodyPart.getInputStream(), writer);
System.out.println("Content inputstream: " + writer.toString());
}

How to send java mail in spring mvc

I have an web application in which i am sending mail to user. Following is my code.
String host = "smtp.gmail.com";
String pwd = "123";
String from = "sender#gmail.com";
String to = "receiver#gmail.com";
String subject = "Test";
String messageText = "This is demo mail";
int port = 587;
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] add = {new InternetAddress(to)};
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setRecipients(Message.RecipientType.TO, add);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText); //Actual msg
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, from, pwd);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
This code is executed on local but fails on server domain. I have search a lot but that solution didn't work for me.
I tried a lot like replacing transport.connect(host, from, pwd); with transport.connect(host, 587, from, pwd); or 465and also String host="smtp.gmail.com"; with static domain IP. but still not working.
can anyone figure out what i am missing..?
Here is working example.
If this didn't work then there must be a problem with your server..
public static void sendEmail(String host, String port, final String userName, final String password, String recipient, String subject, String message, File attachFile) throws AddressException, MessagingException, UnsupportedEncodingException {
// sets SMTP server properties
try {
logger.info("Sending Email to : " + recipient + " Subject :" + subject);
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName, userName));
if (recipient.contains(";")) {
String[] recipientList = recipient.split(";");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String obj: recipientList) {
recipientAddress[counter] = new InternetAddress(obj.trim());
counter++;
}
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
} else {
InternetAddress[] recipientAddress = {
new InternetAddress(recipient)
};
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
}
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFile != null) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(attachFile);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
} catch (Exception e) {
logger.error("ERROR In Sending Email :" + e, e);
}
}

Error sending email with JavaMail

The following code works only when Google's "Allow less secure apps" is ON, if that feature is off I get javax.mail.AuthenticationFailedException, how do I get it to work when that feature is OFF?
public static void main(String[] args) {
String username = "USER-NAME#gmail.com";
String password = "PASSWORD";
String to = "USER-NAME#msn.com";
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.list(System.out);
Session session = Session.getInstance(properties);
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(username));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("This is the subject line!");
msg.setText("This is the actual message");
System.out.println("Sending message...");
Transport.send(msg, username, password);
System.out.println("Message sent!");
} catch (MessagingException ex) {
Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}

Exporting all emails from Gmail with Java Mail API

So i am trying to write a program that will grab all my emails from my email adress and save them to a text file, the problem i am having is grabbing more then 1 email with the Java Mail API.
This is what i use to get an email which works fine, but i want to get every email in my inbox:
public static void checkMail(String username, String password) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", username, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());
} catch (Exception mex) {
mex.printStackTrace();
}
}
If someone could possibly show me how to do this or explain it then that would be greatly appreciated.
If you want all mails in folder inbox do this:
public static void checkMail(String username, String password) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", username, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();
for (Message msg : msgs) {
try {
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
// close folder and store (normally in a finally block)
inbox.close(false);
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
If you want mails from other folders to you have to do the same for all folders.
You get them with store.getDefaultFolder().list() (do this recursive for all folders because folders can have subfolders)
protected void recurseFolders(final Folder folder) {
// folder can hold messages
if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
// process them
}
// folder can hold other folders
if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
for (final Folder subfolder : folder.list()) {
// process them recursive
recurseFolders(subfolder);
}
}
}
Look here: https://github.com/salyh/elasticsearch-river-imap

Cpanel Java Email Client Program

If anyone tried/found working java email/smtp/imap client program that connects to cPanel's email a/cs and send emails out then please share it. It has been a tiresome efforts in trying to find that code online but none of them works fine. I did try more than five varieties of code but nothing worked. Below are few samples:
Sample# 1
String host = "mail.domain.net";
String user = "catch-all#domain.net";
String pass = "xxxx";
String to = "admin#domain.net";
String from = "catch-all#domain.net";
String subject = "Dummy subject";
String messageText = "Dummy body";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", 2525); //25 - default
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
try {
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, pass);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
Error
Sending mail.. Done!javax.mail.MessagingException: Could not connect to SMTP host: mail.dealstock.net, port: 25;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:192)
at com.mail.EmailsSender2.main(EmailsSender2.java:209)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
at com.sun.mai
From the Cpanel account, the designated port is 2525, if secured then 465, but none of the ports work. With post 2525, it does connects, but there is no response and waits for 1-2 minitues and then timeouts. If I change to port 25, then it simply throws above error. With same Cpanel email a/c my another program able to connect and read emails through POP, but failing with sending emails.
Appreciate if you can share your comments/inputs.
I have hostgator, and when creating session, use the following code it works (with no encryption or SSL, not TLS).
btw, port 25 is blocked by my isp (Verizon), and hostgator has it on port 26, not 2525. make sure your hosting company has it running on 2525.
private Session getSession(final EmailConfig emailConfig) {
String port = Integer.toString(emailConfig.getPort());
Properties props = new Properties();
props.put("mail.smtp.host", emailConfig.getHost());
props.put("mail.smtp.port", port);
if (Encryption.SSL == emailConfig.getEncryption()) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
else if (Encryption.TLS == emailConfig.getEncryption()) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
}
return Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailConfig.getUsername(), emailConfig.getDecryptedPassword());
}
});
}
private void sendMessage(Session session, InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bcc, String subject, String text) throws AuthenticationFailedException {
Message message = new MimeMessage(session);
try {
message.setFrom(from);
if (to != null) {
message.setRecipients(Message.RecipientType.TO, to);
}
if (cc != null) {
message.setRecipients(Message.RecipientType.CC, cc);
}
if (bcc != null) {
message.setRecipients(Message.RecipientType.BCC, bcc);
}
message.setSubject(subject);
message.setText(text);
Transport.send(message);
}
catch (AuthenticationFailedException ex) {
log.info("authentication failed", ex);
throw ex;
}
catch (MessagingException e) {
log.info("error sending message", e);
e.printStackTrace();
}
}
This would definitely work for you.
Just call this function to send automated email to client.
In parameter "to" is email address to which you want to send an email.
I usually do it in Maven project. If you are using maven project then import following dependencies.
https://mvnrepository.com/artifact/javax.mail/mail/1.4
final String username = "youremail#gmail.com";
final String password = "yourpassword";
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(to));
message.setSubject(subject);
message.setContent(emailBody, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}

Categories