Java to *get* mail from SMTP sevrer - java

I'm trying to get an email from exchange SMTP server (port 25).
all the examples i saw are to send an email with SMTP while i would like to get (read) an email.
I wrote a code using JAVAMail that get email with impas that work perfect but in the last mooment the demand change to use SMTP for incoming mail.
Java code for IMAP incoming mail
public void getAttachment() throws MessagingException, IOException {
properties.setProperty("exchange server host",host);
properties.put("smtp.gmail.auth", "true");
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
}
);
Store store = session.getStore("imaps");
try {
logger.info(String.format("Going to get connection to exchange server %s for user %s " ,host, user));
store.connect(host, user, password);
}
catch (MessagingException ex){
logger.error(String.format("Unable to connect exchange server {}", host) + ex.getMessage());
logger.error(ex.getStackTrace());
}
Folder inboxFolder = store.getFolder("inbox");
inboxFolder.open(Folder.READ_WRITE);
// search for all "unseen" messages
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
Message[] message = inboxFolder.search(unseenFlagTerm);
Can someone please advise for getting mail with SMTP protocol and not with IMAP?
can it be done ?
Thanks.

You can't.
SMTP is for a client to send email to a server.
In order for a client to receive email from a server, you need to use protocols like POP3 (Post Office Protocol) or IMAP (Internet Message Access Protocol).
Actually, the Wikipedia page for SMTP says as much:
User-level email clients typically use SMTP only for sending messages to a mail server for relaying, typically submit outgoing email to the mail server on port 587 or 465 as per RFC 8314. For retrieving messages, IMAP and POP3 are standard, but proprietary servers also often implement proprietary protocols, e.g., Exchange ActiveSync.

Related

Cannot send email without authentication required

I wrote a simple Java program that uses Java Mail API to send an email.
public static void main(String[] args) {
System.out.println("SimpleEmail Start");
String smtpHostServer = "smtp.gmail.com";
String emailID = "xxxxxx#hotmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, null);
EmailUtil.sendEmail(session, emailID,"SimpleEmail Testing Subject", "SimpleEmail Testing Body");
}
}
EmailUtil class:
public class EmailUtil {
/**
* Utility method to send simple HTML email
* #param session
* #param toEmail
* #param subject
* #param body
*/
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no_reply#example.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("no_reply#example.com", false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
With this implementation, it is said I do not need any password at all so i gave this a tried and it tells me:
com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required
I got this code from an online resources and from what I read,it should be able to send without authentication.
So my question is, do I always need to set a username and password to send mail using JAVA mail?
If no, what am I doing wrong?
It depends on who's running the server.
See https://support.google.com/a/answer/176600?hl=en&vid=0-974788924023-1554173451081; specifically the column labeled 'Gmail SMTP server' (which you're using). Google explicitly says that you have to authenticate to utilize that server. Not doing so gives you this error message.
Once upon a time you could use any mail server to send emails to any email address you wanted.
And then came SPAM. Spammers also could use any mail server to send emails to any email address - and as a mail server operator you do not want spammers to use your server for sending emails (because operating the server costs you money, because your mail server can get blacklisted for spamming).
So today most mail servers require that you
either provide authentication (for sending emails to any email address you want)
or are only allowed to send emails to email addresses hosted by the mail server operator
Google even has two distinct mail servers:
one that requires authentication, that can be used for sending emails to any email address you want (that is the server at smtp.gmail.com)
one that doesn't require authentication, that can only be used for sending emails to Gmail or G Suite users (that is the server aspmx.l.google.com)
It could be that your source dates back to a time when no authentication was required or that the mail server in your source was only used for sending mails to addresses that are hosted at the mail server.
Either way - if you want to use the server smtp.gmail.com for sending mails to any address you must authenticate (or convince google that they should allow you - and only you - to sending emails without authentication, but then: how will google know that it is exactly you who is trying to send mails?)

external email not working exchange and javamail

Good morning to all,
I was try send external email in my organization does not working for me.When i was try internel email address it working fine.. I am getting exception "invalid mail address 5.1.7 unable to relay"
I am also try send with external email via TELNET. Its working fine in TELNET.
Exchange 2013 receive connector anonymous relay was enable.
Properties props = System.getProperties();
props.put(SMTP_HOST_KEY,smtphost);
Session session=null;
System.out.println("Entering into sendSMTPMail=============(props)"+props);
MailAuthentication authorization =new EmailManager().new MailAuthentication();
LogWriter.log("CREATING THE DEFAULT SESSION");
System.out.println("Entering into sendSMTPMail=============(AUTHORIZATION)"+AUTHORIZATION);
System.out.println("Entering into sendSMTPMail=============(authorization)"+authorization);
System.out.println("Entering into sendSMTPMail=============(session)"+session);
if(AUTHORIZATION)session = Session.getInstance(props, authorization);
else session = Session.getInstance(props, null);
session.setDebug(debug);
System.out.println("Entering into sendSMTPMail=============(session)"+session);
OUTPUT in java :
Send is OK
rcpt is Invaild mail address 5.1.7 unable relay
OUTPUT in TELNET:
Send is OK
rcpt is OK
Help is needed......Please let me know what is problem in javacode or exchange 2013
Thanks.....

Cannot send email using Java code on Windows Server 2008 r2?

I have installed SMTP server and IIS Web server on windows 2008 r2 server. I am trying to send a test email using java code through localhost but i am unable to send an email i get the following error not sure what is that i am doing wrong. Apart from installing the SMTP server is there any setting i need to do because i just installed my smtp server and expecting that this code works?
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for marshell#gmail.com
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1862)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1118)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at LotusNotes.SendEmail.main(SendEmail.java:30)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for marshell#gmail.com at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1715)
Java Code:
public static void main(String[] args) {
String to = "marshell#gmail.com";
String from = "imrmsmtpmail";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject Line!");
message.setText("Test email!");
Transport.send(message);
System.out.println("Sent message successfully....");
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
Probably you have to authenticate to send emails to this server.
AFAIK, you aren't providing any user or password in the connection to the server.
I use something like this:
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", true);
properties.setProperty("mail.user", "PUT AN USERNAME HERE");
properties.setProperty("mail.password", "PUT A PASSWORD HERE");
Session session = Session.getDefaultInstance(properties);
And to make sure you have all the parameters working properly before writing the program it is useful to make a telnet to the mail port (25) to make sure you can send an email directly writing the codes into the server.
In the following link you have an example:
http://support.microsoft.com/kb/153119/en
Altough it may sound extremely technical, it worth to try to make sure that the server send emails from your machine with the given parameters: username (or not username at all), destination address, etc.

Can not fetching yahoo mail by POP3 protocol by javamail

I have some code below:
Properties props = System.getProperties();
//set mail protocol
//props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.store.protocol", "pop3s");
//create new store
Session session = Session.getDefaultInstance(props);
//store = session.getStore("imaps");
store = session.getStore("pop3s");
store.connect("pop.mail.yahoo.com", 995, "MyYahooUserName", "MyPassword");
//store.connect("imap.next.mail.yahoo.com", 993, "MyYahooUserName", "MyPassword");
isConnect = true;
It's work when I try IMAP protocol, but with POP3 I got exception below and I don't know why
SEVERE: null
javax.mail.AuthenticationFailedException: EOF on socket
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:208)
at javax.mail.Service.connect(Service.java:295)
at gmailutilities.GmailUtilities.connect(GmailUtilities.java:88)
at gmailutilities.Main.main(Main.java:29)
javax.mail.MessagingException: Not connected
at com.sun.mail.pop3.POP3Store.checkConnected(POP3Store.java:408)
at com.sun.mail.pop3.POP3Store.getDefaultFolder(POP3Store.java:357)
at gmailutilities.GmailUtilities.openFolder(GmailUtilities.java:103)
at gmailutilities.Main.main(Main.java:30)
*Any one know why? Plz help me. Thanks all! *
Note that free Yahoo! Mail accounts do not allow POP3 or SMTP access. You must purchase a Yahoo! Mail Plus account to get POP3 and SMTP access.

Sending a mail to any message server (Gmail, Yahoo etc) without password authentication in Java

We are developing a simple web application in JSF in which there is a need to include a "forget password" module. For the sake of demonstration and simplicity, I tried the following code in Java Servlet. It can send a mail to Gmail and works just fine there is no problem at all. The following is the complete Servlet code.
public class MailClient extends HttpServlet {
private class SMTPAuthenticator extends Authenticator {
private PasswordAuthentication authentication;
public SMTPAuthenticator(String login, String password) {
authentication = new PasswordAuthentication(login, password);
}
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String from = "bhaveshp1980#gmail.com";
String to = "bhaveshp1980#gmail.com";
String subject = "A mail from Java.";
String message = "My first mail from Java.";
String login = "bhaveshp1980#gmail.com";
String password = "password";
Properties props = new Properties();
props.setProperty("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
Authenticator auth = new SMTPAuthenticator(login, password);
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
try {
msg.setText(message);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
Transport.send(msg);
} catch (MessagingException ex) {
Logger.getLogger(MailClient.class.getName()).
log(Level.SEVERE, null, ex);
}
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
Now, the first question is that as soon as a user enters his valid email address, a verification code should be submitted to a specific message server (Gmail, Yahoo and so on) without asking the user for his password (Which is not the case of the above code) which is essential in implementing the "forget password" module in a web application.
The second question is that the above code is bound to sending a mail only to Gmail. If I want to send a mail to some other message server say Yahoo, the statement
props.setProperty("mail.host", "smtp.gmail.com");
needs to be changed to
props.setProperty("mail.host", "smtp.mail.yahoo.com");
[and port no too, regarding others] means that a specific message server to which a message has to be sent need to be recognized properly. Which is the best way to do so?. What is the best method(s) to overcome these issues, please.
Do you change your SMTP settings in your email client each time you send a mail to a different mail provider? No. You don't set the SMTP server to gmail when sending a mail to a gmail.com address. And then set it to yahoo when sending a mail to a yahoo.com address. You set it to your email provider SMTP server, and this SMTP server sends the mail to the appropriate location.
Just choose an SMTP server which agrees to send mails from your application. Sending a dozen per day will be OK with any SMTP provider. But if you send thousands a day, then you could have problems with your provider. Just ask your hosting provider how it goes with outgoing mails (how much it costs, how many per day are accepted, is there a bandwidth limit, etc.)
So you can't do that. That's the whole point of keeping people from spamming, masquerading as users they aren't, and lots of other nasty things.
You need to setup a SMTP server or get your domain hosted on a mail service that you can send mail through. Maybe your ISP or hosting provider provides this already and you just need to sign up for that. Otherwise, there are plenty of places out there that will allow you to send mail from your domain. I use:
http://www.authsmtp.com/
Or you can have google host your domain for free, but they put a limit on the number of messages you can send per day which last time I checked was like 100. So if your site plans on sending more mail than that you need to bump up to paid service like authsmtp.
http://www.google.com/apps/intl/en/business/smb/email.html#utm_campaign=en&utm_source=en-ha-na-us-sk&utm_medium=ha&utm_term=%2Bemail%20%2Bhosting
Basically you need to find a mail server that is in charge of your MX record so emails sent to your domain will get routed to those servers, and so you application can send email from your domain and not get black listed as a spammer because you are doing naughty things.
While you can setup your own smtp server it's just so much easier to use a service, and that gives you a professional look for doing things like customer service, and responding to people when you mail comes from a domain associated with your website and not some johnnyappleseed#gmail.com
You need to do some basic research about how email works from a technical perspective as well. That will help you understand why what I'm talking about is important.
The authentication part you cannot get around. This is configured in the remote server, so unless you use your own mailserver, you have to do what gmail asks you to do. But instead of hardcoding the login/password, you could store them in an (encrypted?) properties file and modify that whenever you want to use another mailserver.
You need to generate a random token and send it as part of the
message. You store the token in the database with an association to
the user's profile. When the user returns to your site with that
token (by entering it into a form, or by clicking a link with that
token as GET parameter) you can be sure the user is authentic and
offer the reset password dialog.
Don't send the message to the smtp server of the recipient, but to
the smtp server of your from email address. So sending it to gmail
would be fine. I would make stmp host url, username and password
configurable, e.g. in a property file.

Categories

Resources