I found that javamail only support socks. Is there any solution I can use to support http proxy?
public class MailConnectionTest {
public static void main(String args[]) throws MessagingException {
Properties props = MailConnectionTest.getProperties();
Session session = Session.getDefaultInstance(props, null);
String protocol = "pop3";
String host = "pop.163.com";
String username = "email username";
String password = "1Qaz2wsx3edc&";
Store store = session.getStore(protocol);
store.connect(host, username, password);
System.out.println("Success");
}
private static Properties getProperties() {
Properties props = System.getProperties();
props.put("mail.debug", "false");
// Proxy
props.put("proxySet", "true");
props.put("http.proxyHost", "proxyAdderss");
props.put("http.proxyPort", "8080");
return props;
}
}
As per the latest release of Javamail API 1.6.2 , JavaMail supports accessing mail servers through a web proxy server and also authenticating to the proxy server. Please see my code below.
import java.io.IOException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
public class ReadMailProxy {
public static void receiveMail(String userName, String password) {
try {
String proxyIP = "124.124.124.14";
String proxyPort = "4154";
String proxyUser = "test";
String proxyPassword = "test123";
Properties prop = new Properties();
prop.setProperty("mail.imaps.proxy.host", proxyIP);
prop.setProperty("mail.imaps.proxy.port", proxyPort);
prop.setProperty("mail.imaps.proxy.user", proxyUser);
prop.setProperty("mail.imaps.proxy.password", proxyPassword);
Session eSession = Session.getInstance(prop);
Store eStore = eSession.getStore("imaps");
eStore.connect("imap.mail.yahoo.com", userName, password);
Folder eFolder = eStore.getFolder("Inbox");
eFolder.open(Folder.READ_WRITE);
Message messages[] = eFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
System.out.println(messages.length);
for (int i = messages.length - 3; i < messages.length - 2; i++) {
Message message = messages[i];
System.out.println("Email Number::" + (i + 1));
System.out.println("Subject::" + message.getSubject());
System.out.println("From::" + message.getFrom()[0]);
System.out.println("Date::" + message.getSentDate());
try {
Multipart multipart = (Multipart) message.getContent();
for (int x = 0; x < multipart.getCount(); x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
System.out.println("Mail have some attachment : ");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
} else {
System.out.println(bodyPart.getContent());
}
}
} catch (Exception e) {
System.out.println("Content: " + message.getContent().toString());
}
message.setFlag(Flag.SEEN, true);
}
eFolder.close(true);
eStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
receiveMail("umesh#yahoo.com", "test123");
}
}
javamail api 1.6 supports web server proxy
set these properties
mail.protocol.proxy.host
mail.protocol.proxy.port
for smtp set as
mail.smtp.proxy.host
mail.smtp.proxy.port
See the JavaMail FAQ:
How do I configure JavaMail to work through my proxy server?
... Without such a SOCKS server, if you want to use JavaMail to access mail servers outside the firewall indirectly, you might be able to use a program such as Corkscrew or connect to tunnel TCP connections through an HTTP proxy server. JavaMail does not support direct access through an HTTP proxy web server.
The implementation only support basic authentication for web proxy. You can find the source code in com.sun.mail.util.SocketFetcher.
Since javamail support NTLM authentication already, it is not hard to support NTLM authentication for web proxy.
Related
I created a method to send email in VB.NET:
Imports System.Threading
Imports System.Net.Mail
Imports System.ComponentModel
Module Module1
Dim smtpList As New ArrayList
Dim counter = 0
Private Sub smtpClient_SendCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
System.Diagnostics.Debug.WriteLine("completed!")
System.Console.WriteLine("completed!")
End Sub
Public Function createSmtp() As SmtpClient
Dim smtp = New SmtpClient()
Dim user = "AKAKAKAKAKAKAKAK"
Dim host = "smtp.mailgun.org"
Dim pass = "akakakakakakakakakakakakakakakakakakakak"
smtp.Host = host
smtp.Port = 587
smtp.Credentials = New System.Net.NetworkCredential(user, pass)
smtp.EnableSsl = True
Return smtp
End Function
Public Sub SendEmail(email As String, bodystuff As String, smtp As SmtpClient)
Dim from As New MailAddress("contat#testsitetetete.com", "Info", System.Text.Encoding.UTF8)
Dim [to] As New MailAddress(email)
Dim message As New MailMessage(from, [to])
message.Body = String.Format("The message I want to send is to this <b>contact: {0}{1}</b>", vbCrLf, bodystuff)
message.IsBodyHtml = True
message.BodyEncoding = System.Text.Encoding.UTF8
message.Subject = "Test email subject"
message.SubjectEncoding = System.Text.Encoding.UTF8
message.Priority = MailPriority.High
' Set the method that is called back when the send operation ends.
AddHandler smtp.SendCompleted, AddressOf smtpClient_SendCompleted
smtp.Send(message)
'smtp.SendMailAsync(message)
counter = counter + 1 ' I know its not thread safe, just to get a counter
System.Console.WriteLine("Counter -> " & counter)
End Sub
Public Sub StartEmailRun()
System.Diagnostics.Debug.WriteLine("StartEmailRun")
'Dim smtp = createSmtp()
Try
For i = 0 To 8
Dim thread As New Thread(
Sub()
Dim smtp = createSmtp()
SendEmail("someamail#testemail.com", "email test", createSmtp())
End Sub
)
thread.Start()
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Main()
System.Diagnostics.Debug.WriteLine("Starting the email sending...")
ThreadPool.SetMinThreads(100, 100) ' just to make sure no thread pool issue or limitation
createSmtp()
StartEmailRun()
Thread.Sleep(300000) ' make the program alive
End Sub
End Module
and I created this same method in java:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class TestMail
{
public static void main(String[] args) throws AddressException, MessagingException, InterruptedException
{
Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "smtp.mailgun.org");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.ssl.trust", "smtp.mailgun.org");
Session session = Session.getInstance(prop, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "akakakakakakakakakak";
String password = "kajdfkjasfkjasdfksjdfksdajfksdfjsdkfjdskfjkW";
return new PasswordAuthentication(username, password);
}
});
final Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("testacount#test.com"));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse("atest#test.com"));
message.setSubject("Mail Subject");
String msg = "This is my first email using JavaMailer";
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
message.setContent(multipart);
for (int i = 0; i < 8; i++)
{
new Thread(new Runnable() {
public void run() {
try {
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("sent...");
}
}).start();
}
while(true)
{
Thread.sleep(1000);
}
}
}
I expected the VB.NET code to sent the emails simultanteously, like the java one does.
But the email sent appears to be sequencial. In the java all the emails are sent simultaneosly.
I think there is some limitation on send multiple emails in the VB.Net code.
Is there a way to send multiple emails at the same time in VB.NET???
p.s. not talking about bbc, because every email is different from another.
we have an Exchange Server and i wanted to test sending a mail with it. But somehow i always get the error:
com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.1 Message rejected as spam by Content Filtering.
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1889)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at Test.sendMailJava(Test.java:89)
at Test.main(Test.java:29)
i tried looking at our exchange if anonymous users were allowed and they are, our Printer also send Mails without any authentification.
Here is my Java code, hope someone can help:
import java.net.URI;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.simplejavamail.email.Email;
import org.simplejavamail.mailer.Mailer;
import org.simplejavamail.mailer.config.ProxyConfig;
import org.simplejavamail.mailer.config.ServerConfig;
import org.simplejavamail.util.ConfigLoader;
public class Test {
public static void main(String[] args) {
//// // TODO Auto-generated method stub
sendMailJava();
}
public static void sendMailJava()
{
String to = "Recipient"
// Sender's email ID needs to be mentioned
String from = "Sender";
// Assuming you are sending email from localhost
String host = "Server Ip-Adress";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
properties.setProperty("mail.imap.auth.plain.disable","true");
properties.setProperty("mail.debug", "true");
Session session = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("Subject");
// Now set the actual message
message.setContent("Content", "text/html; charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
I also tried SimpleMail, but there is the same error.
The Connection to the smtp Server seems to work, but the message cannot be send, cause of the error above. What could it be?
Greetings,
Kevin
Edit:
i found my error, i don't know why our printers can send maisl without errors but it seems i had to whitelist my ip at our exchange server. Code was completely fine.
thanks for the help
I know you are wanting the smtp option, but I have a feeling the issue is how your server is setup and not in your code. If you get the EWS-Java Api, you can log into your exchange server directly and grab mail that way. Below is the code that would make that work:
public class ExchangeConnection {
private final ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // change to whatever server you are running, though 2010_SP2 is the most recent version the Api supports
public ExchangeConnection(String username, String password) {
try {
service.setCredentials(new WebCredentials(username, password));
service.setUrl(new URI("https://(your webmail address)/ews/exchange.asmx"));
}
catch (Exception e) { e.printStackTrace(); }
}
public boolean sendEmail(String subject, String message, List<String> recipients, List<String> filesNames) {
try {
EmailMessage email = new EmailMessage(service);
email.setSubject(subject);
email.setBody(new MessageBody(message));
for (String fileName : fileNames) email.getAttachments().addFileAttachment(fileName);
for (String recipient : recipients) email.getToRecipients().add(recipient);
email.sendAndSaveCopy();
return true;
}
catch (Exception e) { e.printStackTrace(); return false; }
}
}
In your code you just have to create the class, then use the sendEmail method to send emails to whomever.
Your JavaMail code is not authenticating to your server, which may be why the server is rejecting the message with that error message. (Spammers often use open email servers.)
Change your code to call the Transport.send method that accepts a user name and password.
Can any one help me with a java code where i want that my html code to be added in body of the mail and the mail client should pop up so that a person can enter the To: and can edit the body if needed.
I have tried this code but this one just sends the mail.What i want is the my mail client should popup with body already entered.
package you;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
public class test1 {
public void fnSendMail(String Status) throws IOException, InvalidFormatException, URISyntaxException {
String htmlContent = null;
if (Status.equals("Completed")) {
htmlContent = "<html><br>Below is Test Execution Report.<br>Please find the attached for Detailed Results"
+ "<br><br><table border='1' cellpadding='2' cellspacing='3' width='40%' bordercolor='#999999' style='border-collapse: collapse;'>"
+ "<tr><th>SNo</th><th>Run_Method</th><th>abc_name</th><th>Execution_Status</th></tr>" + "</table>"
+ "<br><br><br><h3 style='color:FireBrick;'>Please do not respond to this mail </h3></html>";
} else {
htmlContent = "<html><br>" + "<h3 style='color:FireBrick;'>Automation got failed due to some issue, hence "
+ "Please verify Maven Errors.<br><br>Execution Status till failure is attached.</h3></html>";
}
String from = "abc#cdf.com";
String host = "x.y.z";
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));
Multipart multipart = new MimeMultipart();
BodyPart messageBodyText = new MimeBodyPart();
message.setSubject("CSI API Automated Testing Report is " + Status);
messageBodyText.setContent(htmlContent, "text/html");
multipart.addBodyPart(messageBodyText);
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
public static void main(String[] args) {
test1 test2= new test1();
try {
test2.fnSendMail("Completed");
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
}
Any other way to do this will also work, but i need is java and javascript only
Instead of calling Transport.send you have to call MimeMessage.saveChanges then use MimeMessage.writeTo to save it to the filesystem as '.eml'. Then open that file with java.awt.Desktop.open to launch the email client. Your system must have a mime association with eml or the open call will fail.
If the O/S mime type for eml is not set to something like outlook.exe /eml %1 then you might have to resort to using the process API to launch outlook directly using the eml switch. For example, if you want to preview the foo.eml draft message then the command would be:
outlook.exe /eml foo.eml
You'll have to handle clean up after the email client is closed.
You also have to think about the security implications of email messages being left on the file system.
I am testing the Microsoft Exchange Web Service Java API (version 1.2) to read mails from a server. Here is my code:
String url = "https://my-server/EWS/exchange.asmx";
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.setTraceEnabled(true);
service.setCredentials(new WebCredentials("user", "password"));
service.setUrl(url.toURI());
Mailbox mailbox = new Mailbox("foo#bar.com");
FolderId folder = new FolderId(WellKnownFolderName.Inbox, mailbox);
ItemView view = new ItemView(10);
view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);
FindItemsResults<Item> items = service.findItems(folder, view);
Unfortunately, this code throws the following error:
Exception in thread "main" microsoft.exchange.webservices.data.EWSHttpException: Connection not established
at microsoft.exchange.webservices.data.HttpClientWebRequest.throwIfConnIsNull(Unknown Source)
at microsoft.exchange.webservices.data.HttpClientWebRequest.getResponseCode(Unknown Source)
at microsoft.exchange.webservices.data.EwsUtilities.formatHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeServiceBase.traceHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeServiceBase.processHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(Unknown Source)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.findItems(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.findItems(Unknown Source)
at foo.bar.TestMail.main(TestMail.java:52)
I'm not able to understand what is wrong with the current code. Do you have any clue, or at least some tests to try?
Note that the web-service (https//my-server/exchange.asmx) is accessible to my Java code.
Not sure if it can help, but I've found that in the traces displayed by the logs:
<Trace Tag="EwsResponse" Tid="1" Time="2013-01-28 10:47:03Z">
<html><head><title>Error</title></head><body>The function requested is not supported
</body></html>
</Trace>
EDIT
I've made another test. This time, I use the defaults credentials - so my own email account - using service.setUseDefaultCredentials(true); instead of setting the WebCredentials object. The connection is still not established, but I get another error (I've took only the interesting part of the trace log):
<h1>You are not authorized to view this page</h1>
You do not have permission to view this directory or page using the credentials that you supplied because your Web browser is sending a WWW-Authenticate header field that the Web server is not configured to accept.
(...)
<h2>HTTP Error 401.2 - Unauthorized: Access is denied due to server configuration.<br>Internet Information Services (IIS)</h2>
Of course, I can't access nor change anything on the Exchange server side. Is there a way to make the authentication successful?
The problem is due to the authentication scheme used. By default, EWS uses NTLM, but my Exchange server is not configured to accept this kind of authentication. I have to use LDAP authentication.
I got the above mentioned error and spend many hours trying to fix it. My ultimate solution was to give up on EWS Version 1.2 completely and use the following javax.mail code like this:
package javaapplication4;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
public class JavaApplication4 {
public static void main(String[] args) throws Exception {
new JavaApplication4().send_email();
}
private void send_email() throws Exception
{
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.yourserver.net");
props.put("mail.from", "yourusername#youremailaddress.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.enable", "false");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
Authenticator authenticator = new Authenticator();
props.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
Session session = Session.getInstance(props, authenticator);
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, "yourusername#youremailaddress.com");
// also tried #gmail.com
msg.setSubject("JavaMail ssl test");
msg.setSentDate(new Date());
msg.setText("Hello, world!\n");
Transport transport;
transport = session.getTransport("smtp");
transport.connect();
msg.saveChanges();
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;
public Authenticator() {
String username = "yourusername#youremailaddress.com";
String password = "yourpassword";
authentication = new PasswordAuthentication(username, password);
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
}
You will need to get the javamail-1.4.7 and load the mail.jar from (http://www.oracle.com/technetwork/java/index-138643.html) into the project.
One thing we did which shed light on the situation is download Thunderbird mail client which can auto-discover information about the exchange server to make sure all of our settings were right.
This is an Example of EWS JAVA api 1.2,This is one of the ways you can try
package com.ea.connector.exchange;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import microsoft.exchange.webservices.data.BasePropertySet;
import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemSchema;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.LogicalOperator;
import microsoft.exchange.webservices.data.OffsetBasePoint;
import microsoft.exchange.webservices.data.PropertySet;
import microsoft.exchange.webservices.data.SearchFilter;
import microsoft.exchange.webservices.data.SortDirection;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WebProxy;
import microsoft.exchange.webservices.data.WellKnownFolderName;
import org.apache.commons.httpclient.NTCredentials;
import com.ea.connector.exchange.bean.ExchangeConnectionParamBean;
import com.ea.connector.exchange.util.ExchMessageProperties;
import com.ea.connector.net.ExchGetItemRequest;
public class Test {
protected static ArrayList<String> propertiesToFetch = new ArrayList<String>();
private static ExchangeService mService;
// private Settings mSettings;
//
// private int imailCount;
private Date dStartDate;
private Date dEndDate;
private static ExchangeConnectionParamBean objParamBean;
public void setPropertiesToBeFetched(List<String> filter) {
propertiesToFetch.addAll(filter);
}
public Date getConnectorStartDate() {
return dStartDate;
}
public void setConnectorStartDate(Date dStartDate) {
this.dStartDate = dStartDate;
}
public ExchangeConnectionParamBean getParamBean() {
return objParamBean;
}
public void setParambean(ExchangeConnectionParamBean objParambean) {
Test.objParamBean = objParambean;
}
public Date getConnectorEndDate() {
return dEndDate;
}
public void setConnectorEndDate(Date dEndDate) {
this.dEndDate = dEndDate;
}
public static void main(String []args) throws URISyntaxException,Exception
{
setCredentialsAndGetExchRequest();
System.out.println("conncection established");
}
protected static ExchGetItemRequest setCredentialsAndGetExchRequest() throws URISyntaxException,Exception{
#SuppressWarnings("unused")
FindItemsResults<Item> resultMails;
mService = new ExchangeService();
mService.setUrl(new URI("https://outlook.office365.com/EWS/Exchange.asmx"));
WebProxy paramWebProxy=new WebProxy("ptbproxy.domain.com",8080);
mService.setWebProxy(paramWebProxy);
ExchangeCredentials cred = new WebCredentials("EA_Test_mailbox#domain.com","Zuxu0000");
NTCredentials ntCredentials = new NTCredentials("EA_Test_mailbox#domain.com","Zuxu0000", "",
"");
mService.setCredentials(cred);
// ProxyHost httpProxy=new ProxyHost("ptbproxy.domain.com",8080);
// UsernamePasswordCredentials cred1=new UsernamePasswordCredentials("EA_Test_mailbox#domain.com","Zuxu0000");
// ExchGetItemRequest req = new ExchGetItemRequest(String.valueOf(new URI("http://outlook.office365.com/EWS/Exhanges.asmx")),ntCredentials);
ExchGetItemRequest req = new ExchGetItemRequest("https://outlook.office365.com/EWS/Exhange.asmx",ntCredentials);
SearchFilter filter = getSearchFilter();
PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly);
ItemView itemView = new ItemView(1000, 0, OffsetBasePoint.Beginning);
itemView.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);
itemView.setPropertySet(propertySet);
//mService.setTimeout(500000);
req.setProperties(new ExchMessageProperties().getExchMessageProperties(propertiesToFetch));
/*Fetching of mail ids start here*/
resultMails = getMails(filter, itemView);
return req;
}
protected static SearchFilter getSearchFilter() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date d1 = sdf.parse("2014-11-04 00:00:00");
Date d2 = sdf.parse("2014-11-05 00:00:00");
SearchFilter greaterThanEq = new SearchFilter.IsGreaterThanOrEqualTo(
ItemSchema.DateTimeReceived,sdf.format(d1));
SearchFilter lessThan = new SearchFilter.IsLessThan(
ItemSchema.DateTimeReceived, sdf.format(d2));
SearchFilter mailFilter = new SearchFilter.IsEqualTo(
ItemSchema.ItemClass, "IPM.Note");
return new SearchFilter.SearchFilterCollection(LogicalOperator.And,
greaterThanEq, lessThan, mailFilter);
}
private static FindItemsResults<Item> getMails(SearchFilter searchFilter,
ItemView itemView) throws Exception {
FindItemsResults<Item> items = null;
int count = 0;
int maxTries = 3;
while (true) {
try {
items = mService.findItems(WellKnownFolderName.Inbox,
searchFilter, itemView);
break;
} catch (Exception e) {
if (++count == maxTries)
throw e;
}
}
return items;
}
}
i'm trying the very simple Email Client in java.
When i launch the programe i have an error message:
Exception in thread "main" javax.mail.AuthenticationFailedException: EOF on socket
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:146)
at javax.mail.Service.connect(Service.java:297)
at javax.mail.Service.connect(Service.java:156)
at SimpleEmailClient2.main(SimpleEmailClient2.java:21)
Java Result: 1
Why?
i use Gmail account and i set the POP and IMAP enabled
What could be the possible error in my code?
Thank you
here is the code:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class SimpleEmailClient2 {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
String host = "pop.gmail.com";
String provider = "pop3";
Session session = Session.getDefaultInstance(props, new MailAuthenticator());
Store store = session.getStore(provider);
store.connect(host, null, null);
Folder inbox = store.getFolder("INBOX");
if (inbox == null) {
System.out.println("No INBOX");
System.exit(1);
}
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("Message " + (i + 1));
messages[i].writeTo(System.out);
}
inbox.close(false);
store.close();
}
}
class MailAuthenticator extends Authenticator {
public MailAuthenticator() {
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("email#gmail.com", "password");
}
}
I don't believe gmail supports the pop3 provider; you have to use pop3s instead. Otherwise this should work fine.
Oracle has information on connecting javamail to gmail here.
Specifically it looks like you're failing when trying to establish the connection, likely because you don't specify a username/password to connect to. Try connecting using something like:
store.connect(host, "user618111#gmail.com", "[myPassword]");