Javamail, Transport.send() very slow - java

I have written a method for sending emails in bulk but it is very very slow (around 3 mails every 10 seconds). I want to send thousands of mails. Is there any way to do this much more faster?
I am using gmail now but only for test, finally I want to send using my own SMTP server.
Here is the code:
public boolean sendMessages()
{
try
{
Session session = Session.getInstance(this._properties, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(this.getFrom()));
message.setSubject(this.getSubject());
message.setText(this.getBody());
for (int i = 0, c = this._addresses.size(); i < c; i++)
{
message.setRecipient(Message.RecipientType.TO, new InternetAddress(this._addresses.get(i)));
Transport.send(message);
}
return true;
}
catch(AuthenticationFailedException e) {
e.printStackTrace();
return false;
}
catch(MessagingException e) {
e.printStackTrace();
return false;
}
}

Ok, thank you for your suggestions.
My solution is:
Transport transport = session.getTransport("smtp");
transport.connect(this._properties.getProperty("mail.smtp.host"),
Integer.parseInt(this._properties.getProperty("mail.smtp.port")),
this._properties.getProperty("mail.smtp.user"),
this._properties.getProperty("mail.smtp.password"));
Address[] addr = new Address[this._addresses.size()];
for (int i = 0, c = this._addresses.size(); i < c; i++)
{
addr[i] = new InternetAddress(this._addresses.get(i));
}
transport.sendMessage(message, addr);

Related

session.getDefaultInstance() is giving me noClassDefFound?

I've been constructing a software that will send an email verification code, however when ever I try to run it I get an error on this line ' newSession = Session.getInstance(properties,null);'
Does anyone knows why this is happening, and would also be willing to give me some pointers in how I could fix this?
public void emailVerification()
{
int min = 0;// sets a minimum number for range
int max = 9;//sets maximum number for range
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);// generates a random number
int random_int2 = (int)Math.floor(Math.random()*(max-min+1)+min);// generates another random number
int random_int3 = (int)Math.floor(Math.random()*(max-min+1)+min);// generates another random number
int random_int4 = (int)Math.floor(Math.random()*(max-min+1)+min);// generates the final random number
String randomDigit1 = random_int+"";
String randomDigit2 = random_int2+"";
String randomDigit3 = random_int3+"";
String randomDigit4 = random_int4+"";
allDigits = randomDigit1+randomDigit2+randomDigit3+randomDigit4;
Session newSession = null;
MimeMessage mimeMessage = null;
Properties properties = new Properties();
properties.put("mail.smtp.auth","true");
properties.put("mail.smtp.starttls.enable","true");
properties.put("mail.smtp.port","547");
String emailHost = ("smtp.gmail.com");
String myAccountEmail = ("**********#*****.com");
String myAccountPassword = ("*******");
newSession = Session.getInstance(properties,null);
String[] emailRecipients ={signUpAccount};
String emailSubject = "Verification Code";
String emailBody = allDigits;
mimeMessage = new MimeMessage(newSession);
for(int i =0; i<emailRecipients.length;i++)
{
try
{
mimeMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(emailRecipients[i]));
}
catch (javax.mail.MessagingException me)
{
me.printStackTrace();
}
}
try
{
mimeMessage.setSubject(emailSubject);
}
catch (javax.mail.MessagingException me)
{
me.printStackTrace();
}
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();
try
{
multipart.addBodyPart(bodyPart);
}
catch (javax.mail.MessagingException me)
{
me.printStackTrace();
}
try
{
mimeMessage.setContent(multipart);
}
catch (javax.mail.MessagingException me)
{
me.printStackTrace();
}
try
{
Transport transport = newSession.getTransport("smtp");
try
{
transport.connect(emailHost, myAccountEmail, myAccountPassword);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
JOptionPane.showInputDialog("The verification Email has been sent");
}
catch (javax.mail.MessagingException me)
{
me.printStackTrace();
}
}
catch (javax.mail.NoSuchProviderException nspe)
{
nspe.printStackTrace();
}
}

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);

Java sending a mail via tomcat server

I'm trying to send a mail via android application, the mail has to be sent through my server (because the mail API of Gmail need username and password so, I don't want that my data be in the code itself)
but I got this error of socketTimeOutException.
I can increase the timeout but then I cannot do anything until the response received, and it takes like 25 seconds.
and if I put the sending function in a thread it doesn't send the mail at all.
this is the code of the server:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JSONObject res = new JSONObject();
try {
System.out.println("Post ForgotMypass");
Mongo mongo = new Mongo(LogIn.host, 27017);
DB db = mongo.getDB("Users");
DBCollection collection = db.getCollection("usersCollection");
// get a myUser object and cheack for jobs
String json = request.getParameter("JSONObj");
JSONParser jp = new JSONParser();
JSONObject temp = (JSONObject) jp.parse(json);
String mail = (String) temp.get("mail");
if (mail != null) {
BasicDBObject searchQuer = new BasicDBObject();
searchQuer.put("Mail", mail);
DBObject Item = collection.findOne(searchQuer);
if (Item != null) {
JSONParser jp2 = new JSONParser();
JSONObject Is = (JSONObject) jp2.parse(Item.toString());
JSONObject I = (JSONObject) Is.get("_id");
String id = (String) I.get("$oid");
if (id != null) {
String Dmail = URLDecoder.decode(mail, "UTF-8");
SendMailSSL.SendMail(Dmail, 4, id);
StringWriter out = new StringWriter();
res.put("Status", "true");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
System.out.println("mail sent succesfully");
} else {
StringWriter out = new StringWriter();
res.put("Status", "falseNoMail");
System.out.println("ver false no mail");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
} else {
StringWriter out = new StringWriter();
res.put("Status", "ObjectdoesntExists");
System.out.println("ver ObjectdoesntExists");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
} else {// id is null
StringWriter out = new StringWriter();
res.put("Status", "falseIdNUll");
System.out.println("ver falseIdNUll");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
} catch (Exception e) {
e.printStackTrace();
StringWriter out = new StringWriter();
res.put("Status", "false");
System.out.println("ver false");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
}
and:
public static void SendMail(String to, int typeOfMessage, String UserID) {
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() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("adress"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
/*
* all the type of messages
*/
if (typeOfMessage == 1) {
message.setSubject("title");
message.setText("text");
}else if (typeOfMessage == 2){
message.setSubject("title");
message.setText("text");
}else if (typeOfMessage == 3){
message.setSubject("title");
message.setText("text");
}else if (typeOfMessage == 4){
message.setSubject("title");
message.setText("text");
}
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
so, somebody has an idea how to avoid that problem.
more specific , to send the mail via the server but after that, I sent the response somehow to the android client, so he doesn't have to wait for 25 seconds.
thanks
Your android app should send the request in a separate thread, because sending it through the main thread will block the GUI of your app. The Tomcat-Server handles requests in different threads by default. Thus you need not starting separate threads inside of the request handling. You can start a new thread like this (see docs for java.lang.Thread):
Thread theThread = new Thread(new Runnable() {
#Override
public void run() {
// send the request to the tomcat server
}
});
theThread.start();

user is receiving same email twice in java

I am using the code below to send emails using java ,my project is running on a tomcat server.
the problem that user is receiving same email twice.
after some research it seems that java is sending email twice,any one can help me how I handle it?
Properties props;
Session session;
try {
props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "....");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.connectiontimeout", "2000");
props.put("mail.smtp.timeout", "2000");
props.setProperty("charset", "utf-8");
session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
// session.setDebug(true);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
if (!to.equals("") && to != null) {
String[] toArray = to.split(";");
InternetAddress[] toList = new InternetAddress[toArray.length];
for (int i = 0; i < toArray.length; i++) {
toList[i] = new InternetAddress(toArray[i]);
}
message.addRecipients(Message.RecipientType.TO, toList);
}
if (!cc.equals("") && cc != null) {
String[] ccArray = cc.split(";");
InternetAddress[] ccList = new InternetAddress[ccArray.length];
for (int i = 0; i < ccArray.length; i++) {
ccList[i] = new InternetAddress(ccArray[i]);
}
message.addRecipients(Message.RecipientType.CC, ccList);
}
message.setSubject(subject);
//message.setText(emailBody);
message.setContent(emailBody, "text/html; charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
A way to solve errors when sending an email and, moreover, when you want to do something that has been already done from someone else, is by using a library. Open source libraries are used from a lot of developers and their bugs are all the times less than a custom source code. I would suggest you to use Apache commons Email Library.
Using this link you can find a lot of examples.

SMTP mail code is working fine in Android ICS but not in Gingerbread?

I have written a code to send mail through SMTP, The mail is sent from android ICS devices, but from Gingerbread device mail is not sent.
Can anyone go through the code and help me...
Firstly I m calling sendmail() method of GMailOauthSender class.
class GMailOauthSender {
private Session session;
public SMTPTransport connectToSmtp(String host, int port,
String userEmail, String oauthToken, boolean debug)
throws Exception {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "false");
session = Session.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
final String emptyPassword = null;
transport.connect(host, port, userEmail, emptyPassword);
byte[] response = String.format("user=%s\1auth=Bearer %s\1\1",
userEmail, oauthToken).getBytes();
response = BASE64EncoderStream.encode(response);
transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235);
return transport;
}
public synchronized void sendMail(String subject, String body,
String user, String oauthToken, String recipients, String cc) {
try {
spinner = ProgressDialog.show(FeedbackActivity.this, "",
getResources().getString(R.string.sending_mail), false, true);
new SendMailTask().execute(subject, body, user, oauthToken,
recipients, cc);
} catch (Exception e) {
Log.d("exception inside send mail method", e.toString());
}
}
class SendMailTask extends AsyncTask<Object, Object, Object> {
#Override
protected Object doInBackground(Object... params) {
String subject = (String) params[0];
String body = (String) params[1];
String user = (String) params[2];
String oauthToken = (String) params[3];
String recipients = (String) params[4];
String cc = (String) params[5];
try {
SMTPTransport smtpTransport = connectToSmtp(
"smtp.gmail.com", 587, user, oauthToken, false);
for(int i = 0; i< attachedFiles.size(); i++){
File file = new File(attachedFiles.get(i).getFilePath());
addAttachment(multipart, file);
}
MimeMessage message = new MimeMessage(session);
message.setSender(new InternetAddress(user));
message.setSubject(subject);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(body + "\nThanks\n"+user+"\n\n"+getResources().getString(R.string.signature_text));
multipart.addBodyPart(mbp1);
message.setContent(multipart);
if (recipients.indexOf(',') > 0){
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipients));
}else{
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(recipients));
}
if(cc != null && cc.length() >0){
if (cc.indexOf(',') > 0){
message.addRecipients(Message.RecipientType.CC,
InternetAddress.parse(cc));
}else{
message.addRecipient(Message.RecipientType.CC,
new InternetAddress(cc));
}
}
smtpTransport.sendMessage(message,
message.getAllRecipients());
spinner.dismiss();
finish();
return new Object[] { smtpTransport, message };
} catch (Exception e) {
spinner.dismiss();
finish();
}
return null;
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
if(result != null){
Toast.makeText(FeedbackActivity.this, getResources().getString(R.string.mail_sent), Toast.LENGTH_LONG).show();
}else{
Toast.makeText(FeedbackActivity.this, getResources().getString(R.string.mail_not_sent), Toast.LENGTH_LONG).show();
}
}
}
}

Categories