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());
}
Related
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);
}
I'm trying to get all mails of my gmail but I can only get 250. According to https://javaee.github.io/javamail/FAQ#gmailsettings, I had already set the number of mail limit to 1000 but it still only fetch 250 mails. Here's my code
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
public class Getreply {
public static void check() {
String host = "pop.gmail.com";
String mailStoreType = "pop3";
String username = "";
String password = "";
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(host, username, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
Object body = message.getContent();
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + body );
}
//close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Does anyone know how can I get all?
Check your POP settings in Gmail or switch to IMAP.
I have just test it if you have no need to use pop you should try imap
your chech method will be like this below. Idid test it i can my mails without restriction. But also if you configure your gmail account for a specific number you will receive that number.
public static void check() {
String host = "imap.gmail.com";
String username = "user";
String password = "passwd";
try {
//create properties field
Properties properties = new Properties();
properties.setProperty("mail.imap.ssl.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("imap");
store.connect(host, username, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
Object body = message.getContent();
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + body );
}
//close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
I am reading email from gmail.com. i have read some of the mail successfully but after a while i got this,
java.lang.ClassCastException:
javax.mail.internet.MimeMultipart cannot be cast to java.lang.String
at emailIngestion.EmailIngestion.check(EmailIngestion.java:66)
at emailIngestion.EmailIngestion.main(EmailIngestion.java:106).
Actually my requirement is to store content into a variable and then store it in arraylist and then again write it to a file... i have implemented it using this code so if any better ideas are there please share me.
public class EmailIngestion {
static ArrayList<EmailModel> contentList=new ArrayList<EmailModel>();
static ArrayList<EmailModel> metaDataList= new ArrayList<EmailModel>();
public static void check(String host, String storeType, String user,
String password) throws IOException
{
FileWriter fw= new FileWriter("C:\\Users\\Admin\\Desktop\\murtaza_metadata.csv",true);
FileWriter fw1= new FileWriter("C:\\Users\\Admin\\Desktop\\murtaza_content.txt",true);
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages();
int emailNumber;
String mailContent = null,from = null,to = null,mailContentType = null,subject = null;
Date recievedDate= new Date();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("Subject is"+message.getSubject());
subject = message.getSubject();
from = message.getFrom()[0].toString();
mailContentType=message.getContentType();
recievedDate=message.getSentDate();
to=InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
emailNumber=message.getMessageNumber();
metaDataList.add(new EmailModel(from, to, subject, mailContentType, recievedDate,emailNumber));
fw.write(emailNumber+"\001"+from+"\001"+subject+"\001"+recievedDate+mailContentType+"\001"+" \n");
fw.flush();
if(message.isMimeType("multipart/*")){
Multipart multipart = (Multipart) message.getContent();
for (int x = 0; x < multipart.getCount(); x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
mailContent=(String) bodyPart.getContent();
System.out.println(mailContent);
}
}
else{
mailContent=(String) message.getContent();
System.out.println(message.getContent());
}
contentList.add(new EmailModel(mailContent, emailNumber));
fw1.write(emailNumber+","+mailContent+"\n");
}
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "abcd#gmail.com";// change accordingly
String password = "******";// change accordingly
check(host, mailStoreType, username, password);
}
}
Thanks in advance
If the services are fluctuating then its definitely not stable. Which version of 1.3 you are using? As you are using one node make sure that you have master and worker services are installed and running. This you can see from your cluster manager. The info from logs is not informative enough to nail down the issue.
I am trying to download attachments from Hotmail messages and getting the following exception: com.sun.mail.util.DecodingException: BASE64Decoder: Error in encoded stream: needed 4 valid base64 characters but only got 2 before EOF, the 2 most recent characters were: "JV". for every message with an attachment. I tried setting "mail.imaps.partialfetch" to "false" but it did not work, here is the code i'm using:
public class imapHotmail {
private static Object m;
public static void main(String[] args) {
java.security.Security
.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
//System.setProperty("mail.mime.decodetext.strict", "false");
//System.setProperty("mail.mime.base64.ignoreerrors", "true");
System.setProperty("mail.imaps.partialfetch", "false");
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.imaps.partialfetch", "false");
try {
Session session = Session.getInstance(props, null);
// session.setDebug(true);
Store store = session.getStore("imap");
System.out.println("connecting....");
store.connect("imap-mail.outlook.com", "soemone#hotmail.com", "pass");
System.out.println("connected");
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();
int x = 1;
for (Message msg : msgs) {
System.out.println(x);
System.out.println(msg.getSubject());
Object content = msg.getContent();
if (content instanceof Multipart) {
Multipart multipart = (Multipart) content;
for (int i = 0; i < multipart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
System.out.println("saving");
//part.getContent(); this only returns the parts headers and 2 chars from the encoded bodypart
String name = part.getFileName();
File f = new File("C:\\Users\\user\\Desktop\\" + name);
part.saveFile("C:\\Users\\user\\Desktop\\" + name);
System.out.println("saved");
}
}
}
x++;
}
inbox.close(true);
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
here is the output i get if i call part.writeTo(System.out):
Content-Type: application/pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="pdf2.pdf"
JV
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