properties.put("mail.imap.host", host);
properties.put("mail.imap.port", "993");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("imaps");
store.connect(host, username, password);
This code is working well, but if the mail server is down, I got the expection:
javax.mail.MessagingException: * BYE JavaMail Exception: java.io.IOException: Connection dropped by server?;
nested exception is:
com.sun.mail.iap.ConnectionException: * BYE JavaMail Exception: java.io.IOException: Connection dropped by server?
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:731)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at eugene.neocortex.fm.mail.check.CheckingMails.fetch(CheckingMails.java:100)
So I need to check if server is available? And I read the documentation of javax.mail and cant find method, how do I can check if server is alive? Method isConnected() checks if currently connected, but I need to check connection to my mail server before this code or I got exception again on this code string:
Store store = emailSession.getStore("imaps");
I initially tried to write a code to send mail from localhost, but I am not sure how to setup server. Went through help topics regarding that, didn't help much.
Is it possible to write a Java code to send mail from Windows Server 2012?
If not, please please help me setup localhost in my Windows Server 2012. I'm lost.
This is the code that I used:
public static void main(String[] args) throws AddressException, MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", "10.204.10.116");
props.put("mail.smtp.port", "443");
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("abc#gmail.com"));
message.setRecipient(RecipientType.TO, new InternetAddress("xyz#gmail.com"));
message.setSubject("Notification");
message.setText("Successful!", "UTF-8"); // as "text/plain"
message.setSentDate(new Date());
Transport.send(message);
}
}
This is the error that I got:
Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: 10.204.10.116, port: 443;
nested exception is:
java.net.ConnectException: Connection timed out: connect
Not sure what I'm supposed to make of this error.
I am working with SMTP server and found out an issue.
1) SMTP server is not down: In this case, the SMTP server is busy servicing email requests concurrently and continuously for more than 5 minutes (I'm sending bulk mails). At some point of time during servicing, it is not returning or throwing any exceptions to the Java/JavaMail program. In fact, I've experienced this kind of situation in my real time. In case, if I've not set both mail.smtp.timeout and mail.smtp.connectiontimeout properties within my code, it would never return and goes into infinite state.
If i do set my mail.smtp.connectiontimeout and mail.smtp.timeout, how can I test it?
How can we simulate/reproduce this kind of situation? Any ideas?
2) Also another issue is caused by networking issue where I send the request to SMTP form my java code, and it is queued. I am not sure what happens (I dont have a java loop) but the SMTP sends out multiple emails to the same person. Is it because the SMTP did not send back an response? Should the code not timeout after 3000?
Below is my code
props.put("mail.smtp.timeout", 3000);
props.put("mail.smtp.connectiontimeout", 3000);
SMTPTransport transport = (SMTPTransport)session.getTransport("smtp");
/ do some message setting here /
transport.connect();
int SMTPCodeBeforeSendingMessage = transport.getLastReturnCode();
logger.debug("Connection Code for SMTP connection after connect before sending mesasge" + SMTPCodeBeforeSendingMessage);
transport.sendMessage(msg, msg.getAllRecipients());
String SMTPresponse = transport.getLastServerResponse();
logger.debug("SMTP resposne after sending message" + SMTPresponse);
transport.close();
I am trying to send an email using SMTP.
It works fine in my local. But it does not work when i built it on AWS EC2 server.
This is my code to config and send email!
Any idea for me?
try{
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable",true);
props.put("mail.smtp.host","smtp.gmail.com");
props.put("mail.smtp.user","test#gmail.com");
props.put("mail.smtp.password","testpassword");
props.put("mail.smtp.port","587");
props.put("mail.smtp.auth",true);
props.put("mail.smtp.ssl.trust", "*");
String[] to = {toEmail};
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("test#gmail.com"));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i=0; i < to.length; i++ ) { // changed from a while loop
toAddress[i] = new InternetAddress(to[i]);
}
System.out.println("EMAIL TO:"+toEmail);
for( int i=0; i < toAddress.length; i++) { // changed from a while loop
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(content);
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com","test#gmail.com","testpassword");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch(Exception ex){
log.debug("send Email failed", ex);
}
AWS EC2 does not allow normal use of port 25 - the SMTP port.
It is severely throttled.
If you make very very light use of it then you might see sending email off the AWS account working occassionally. But generally it is not reliable
To resolve this problem there are two options
use AWS SES simple email service. Or SNS for some really simple use cases
ask AWS support to remove the restriction https://aws-portal.amazon.com/gp/aws/html-forms-controller/contactus/ec2-email-limit-rdns-request
We were recently bit by this issue as well. AWS by default throttles the number of connections that can originate from ec2 instances. The limitation is part of the EC2 service itself. Ironically it doesn't show any mention of this as a "limit" under the limits section of the EC2 service. It is mentioned on the form though to have this limit removed from your account:
I'm having trouble sending email over port 25 of my Amazon Elastic Compute Cloud (Amazon EC2) instance, or I'm getting frequent timeout errors. How do I remove the port 25 throttle on my EC2 instance?
It's also mentioned on the AWS Service Limits page for EC2:
The removal can be done in minutes once you submit the form to AWS.
References
How do I remove the throttle on port 25 from my EC2 instance?
Amazon Elastic Compute Cloud (Amazon EC2) Limits
I'm using javamail to send emails to a list of recipients, but don't want them to be able to see who else received the email. I also don't want to send it using BCC since then the user doesn't even see themselves in the TO list. I thought this code would do it, but it shows all the recipients in the TO list. Other than creating a loop and sending the emails one at a time, is there another way to do this?
(NOTE: recipients[] is a string array containing the email addresses.)
javax.mail.internet.InternetAddress[] addressTo = new javax.mail.internet.InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new javax.mail.internet.InternetAddress(recipients[i]);
}
msg.setRecipients(javax.mail.Message.RecipientType.TO, addressTo);
No, there isn't a way to do this with email.
You have to explicitly build and send an email iterating by each of your recipients, one of them as the sole member of your addressTo array.
The SMTP protocol doesn't care who's listed in the message and the recipients specified on the RCPT TO command are only used to figure out who to transport the message to. There's nothing stopping you from building the RFC822 message with the To header as you've defined above and then writing a custom SMTP client that send your particular message out but with a different set of recipients. And just because you can send the message doesn't mean a spam filter along the way is going to notice the wonky recipient headers and block the message.
In my experience, JavaMail's SMTP client is really good at sending basic messages without any of the mail tricks you often seen used by mailing list providers and spammers. Those companies spend a lot of effort to make sure they can send messages the way they want but they also are in a constant fight to make sure they're messages are treated as legit email.
Short answer: I'd resort to BCC and if this is for marketing purposes, consider using a company that specializes in this kind of thing.
Why are you concerned about the recipient not seeing his own address? He already knows his his own address, so why is it an issue? BCC was designed to handle exactly the problem you describe. It's been around for decades & sounds like a perfect fit.
Actually, we don't have to manually create InternetAddress objects for Multi Recepients.
InternetAddress api provides a parse() method to do this for us.
Sample code for this is as below,
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
Here parse method creates multiple InternetAddress objects if toAddress contains multiple email addresses seperated by ,(comma).
Check for below API for more details.
http://docs.oracle.com/javaee/6/api/javax/mail/internet/InternetAddress.html#parse(java.lang.String)
Happy Coding. :)
as Message.RecipientType you should use Message.RecipientType.BCC to not showing the every address to every recipient
Google Keywords: Java Mail BCC
Try this:
Session session = Session.getInstance(properties);
Transport transport = session.getTransport("smtp");
String recipient = "ex1#mail.com,ex2#mail.";
String[] recipients = recipient.split(",");
transport.connect(server, username, password);
for (String to : recipients) {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject);
message.setText(body);
message.setContent(body, "text/plain");
message.saveChanges();
transport.sendMessage(message, address);
}
transport.close();
According to the documentation for javax.mail.Transport:
public static void send(Message msg,
Address[] addresses)
throws MessagingException
Send the message to the specified addresses, ignoring any recipients specified
in the message itself.
So you should be able to put the actual delivery addresses (RCPT TO addresses) in the array argument to Transport.send, while putting whatever you want the recipients to see in the message headers via Message.setRecipient, MIMEMessage.addHeader, etc.
If you want different sets of users to see different things, you will have to construct and send a separate message for each set.
You can do this by setting the code as below
message.setRecipients(Message.RecipientType.BCC, toAddrs);
instead of
message.setRecipients(Message.RecipientType.TO, toAddrs);
Place your session creation inside the loop. It will create the session for every user but
it's time complex.