How to send a Bulk email to different email ID's - java

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

Related

JavaMail contact us swing form programming

I want to program a "Contact Us" form in my desktop application (Swing in Netbeans), just like what we find in some websites.
The problem that I faced is the smtp server name. Actually, I want that the user could send me a message without giving his address mail and without requiring that he connects to his account either.
Here a screen shot:
And this is my Submit button action:
#Override
public void actionPerformed(ActionEvent e) {
boolean isSent = true;
try {
//Properties properties = new Properties();
Properties properties = System.getProperties();
// properties.setProperty("mail.smtp.submitter", contactUs.getMailField().getText());
//properties.setProperty("mail.smtp.auth", "false");
properties.setProperty("mail.smtp.host", "localhost");
//properties.put("mail.smtp.user", txtfrom.getText());
//properties.put("mail.smtp.port", txtPort.getText());
//properties.put("mail.smtp.socketFactory.port", txtPort.getText());
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
//Authenticator mailAuthenticator = new MailAuthenticator();
Session mailSession = Session.getDefaultInstance(properties);
Message message = new MimeMessage(mailSession);
InternetAddress fromAddress = new InternetAddress(contactUs.getMailField().getText());
InternetAddress toAddress = new InternetAddress("mancha#gmail.com");
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(contactUs.getSubjectField().getText());
message.setText(contactUs.getMsgField().getText());
Transport.send(message);
} catch (Exception ex) {
contactUs.getErrorMsg().setText("ERROR:" + ex.getMessage());
isSent = false;
}
if (isSent == true) {
contactUs.getSubmitBtn().setEnabled(false);
contactUs.getErrorMsg().setText("Your e-mail has been sent.");
}
}
Of course I google and I found that simple example which causes always problem of connection to smtp server.
First of all, make sure that your smtp server listens on port 25.
you can check it via telnet.
telnet localhost 25
if you do not have any, install a smtp service to your system.
if you have, check your smtp services security settings to connect it
Firstly check that your mail server is up and running by running
telnet localhost 25
Secondly you don't want to set the fromAddress as the users 'prescribed' email as that would require the account exists on your local mail server (As often people contacting you wouldn't already be on your system). Instead, temporarily hard code the fromAddress to an email address you know exists on your mail server and just append the users email address to the email.
An example of what you might want to do
final String FROM_EMAIL_ADDRESS = yourexistingemail#mailserver.com;
InternetAddress fromAddress = new InternetAddress(FROM_EMAIL_ADDRESS);
message.setText(contactUs.getMsgField().getText(), "\nFrom: " + contactUs.getMailField().getText());

javax.mail work on PC but not on server

I've search but can't seem to find a similar problem, never mind an answer. I have a web app running on my laptop (windows 8), tomcat7 and it works fine. It sends out the email as expected. I have the same code running on my linux server, also tomcat7 and I get javax.mail.AuthenticationFailedException.
I've done the Authenticator thing from the start:
...
Authenticator mailAuthenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(properties.getProperty("mail.smtp.user"),
properties.getProperty("mail.smtp.password"));
}
};
try {
// Get the default Session object.
Session session = Session.getInstance(properties, mailAuthenticator);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSubject("Subject, whoot whoot!");
mimeMessage.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from")));
//This is an overkill
List<String> emailList = new LinkedList<>();
emailList.add("email#example.com");
for(String item : emailList) {
mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(item));
}
//The body ).(
StringBuilder sbMsg = new StringBuilder("Some text, etc.\n");
sbMsg.append("more text");
Multipart multipart = new MimeMultipart("alternative");
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setContent(sbMsg.toString(), "text/plain");
multipart.addBodyPart(messageBodyPart1);
mimeMessage.setContent(multipart);
Transport transport = session.getTransport(properties.getProperty("mail.transport"));
int port = Integer.parseInt(properties.getProperty("mail.smtp.port"));
//Exception happens on the line below
transport.connect(properties.getProperty("mail.smtp.host"),
port,
properties.getProperty("mail.smtp.user"),
properties.getProperty("mail.smtp.password"));
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
return true;
} catch (Exception e) {
//Pokemon exception handling :(
LOG.log(Level.SEVERE, "Error while sending email", e);
}
The exception happens on transport.connect, and there is no description with the exception :(
I've checked the mail.smtp.user and mail.smtp.password and it is exactly the same :s
Any clues where I can start looking?
Just got an emails and text from Google. GMail thought I was trying to hack my account. I'm glad there is a logical answer to this problem :-)

Mail sending is failed using java

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.

Gmail Imap vs Pop3 when using JavaMail API

I am trying to fetch unread mail from the INBOX from a gmail account. I wrote a small demo program and found that Gmail's pop3 behaves unexpectedly in a number of situations
When you try to get a list of available folders, Pop3 returns just the INBOX and not all the labels while IMAP does it correct. I am in-lining the code here.
POP3
public static Result getPop3FolderList()
{
Properties props = System.getProperties();
props.put("mail.store.protocol", "pop3s");
props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", Application.email);
props.put("mail.pop3.socketFactory", 995);
props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.port", 995);
Session session = Session.getInstance(props,new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Application.email, Application.pwd);
}
});
try{
Store store=session.getStore("pop3");
store.connect(Application.email,Application.pwd);
javax.mail.Folder[] folders = store.getDefaultFolder().list("*");
String opHtml = "<ul>";
for (javax.mail.Folder folder : folders) {
if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
opHtml += "<li>" + folder.getFullName()+ "+" + folder.getMessageCount() + "</li>";
}
}
opHtml += "</ul>";
return ok(opHtml).as("text/html");
} catch(MessagingException e) {
return ok("Error in getting list.<br />" + e.getMessage()).as("text/html");
}
}
IMAP
public static Result getImapFolderList()
{
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props,new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Application.email, Application.pwd);
}
});
javax.mail.Store store = session.getStore("imaps");
store.connect("imap.gmail.com", Application.email, Application.pwd);
javax.mail.Folder[] folders = store.getDefaultFolder().list("*");
String opHtml = "<ul>";
for (javax.mail.Folder folder : folders) {
if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
opHtml += "<li>" + folder.getFullName()+ ":" + folder.getMessageCount() + "</li>";
}
}
opHtml += "</ul>";
return ok(opHtml).as("text/html");
} catch (MessagingException e) {
return ok("Error in getting list.<br />").as("text/html");
}
}
Even When retrieving the mail, when I put the unread mails filter, gmail returns a number of read mail that are not even part of inbox but long archived ones. IMAP, on the other hand behaves expectedly.
Additional Info : I have enabled pop3 only for the new mail and not from the beginning
Am I using the pop3 wrong or is it broken in gmail?
Apparently, POP3 doesn't handle folders. I had the same problem when accessing Exchange mailboxes - IMAP gets folders, POP3 only gets the Inbox.
I found more info here: How to retrieve gmail sub-folders/labels using POP3?

How to change JavaMail port

I'm writing a small Java app using JavaMail that sends the user an automated email. They can choose between (for now) two ports: 25 and 587. The port can be selected via a radio button on the GUI.
I added a test button to allow the user to test the email settings (including port). However, for some reason, once the user tries to send a test email, the port can't be changed. Javamail will always use the port of the original test email.
Example: User tries to send an email on port 25 and JavaMail says it can not connect on port 25 (for example, the SMTP host uses another port). User clicks port 587, and tries to send a new email. JavaMail throws an error saying it can not connect on port 25, again.
I'm kind of stumped as to why. Every time a new test email is sent an entirely new SendMailUsingAuthentication object is created. Within that class the properties are always reset to the proper port. Whenever I debug, as far as I can see, all variables are correct and associated with the correct port. Is there something going on inside of Transport that I'm missing?
In the front end GUI:
private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {
int port = port25RadioButton.isSelected() ? PORT_25 : PORT_587;
notifier = new SendMailUsingAuthentication(hostNameTextField.getText(),
userTextField.getText(), getPassword(), emailTextField.getText().split(","),port);
Thread wait = new Thread(new Runnable() {
public void run() {
try {
changeStatusText("Sending test email...");
notifier.postTestMail();
changeStatusText("Test email sent.");
} catch (AddressException ex) {
changeStatusText("Error. Invalid email address name.");
} catch (MessagingException ex) {
changeStatusText("SMTP host connection refused.");
System.err.println(ex.getMessage());
} catch (Exception ex) {
System.err.println(ex);
}
}
});
wait.start();
}
In the email sender class:
public void postTestMail() throws MessagingException, AddressException{
String[] testReciever = new String[1];
testReciever[0] = emailList[0];
postMail(testReciever, "Test email.", "Your email settings are successfully set up.", emailFromAddress);
}
private void postMail(String recipients[], String subject,
String message, String from) throws MessagingException, AddressException {
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.port", smtpPort);
props.put("mail.smtp.host", smtpHostName);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", true);
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(false);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
This happens because you're using getDefaultInstance() which says:
Get the default Session object. If a default has not yet been setup, a new Session object is created and installed as the default.
And that the Properties argument is "used only if a new Session object is created."
So the first time you invoke getDefaultInstance it uses your specified port. After that, the Session has already been created, and subsequent calls to getDefaultInstance will return that same session, and ignore the changed properties.
Try using Session.getInstance() instead of getDefaultInstance(), which creates a new Session each time, using the supplied properties.
It pays to read the javadocs very carefully.
Tip for anyone else still having issues, we were using Session.getInstance and the port was still defaulting to 25.
Turns out, we were setting the prop value as a Long when it needs to be a String
It didn't error, warn or log, just defaulted to 25.
I think "Transport.send(msg)" wont be taking into account the connection details that you are providing in your properties. It will use its connection that is defined by default.
The java doc says
"Note that send is a static method that creates and manages its own connection. **Any connection associated with any Transport instance used to invoke this method is ignored and not used. This method should only be invoked using the form Transport.send(msg);, and should never be invoked using an instance variable. "**
Instead, I have tried with Transport.connect(smtphost,smtpport,user,password) and it works pretty well.
Plz compare two methods of Session class: Session.getDefaultInstance(Properties, Authenticator) and Session.getInstance(Properties, Authenticator)

Categories