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.
Related
Following code sample found in:
https://www.codejava.net/java-ee/javamail/embedding-images-into-e-mail-with-javamail
The images are attached to the email, but not embedded in the html of the email.
package net.codejava.mail;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
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;
/**
* This utility class provides a functionality to send an HTML e-mail message
* with embedded images.
* #author www.codejava.net
*
*/
public class EmbeddedImageEmailUtil {
/**
* Sends an HTML e-mail with inline images.
* #param host SMTP host
* #param port SMTP port
* #param userName e-mail address of the sender's account
* #param password password of the sender's account
* #param toAddress e-mail address of the recipient
* #param subject e-mail subject
* #param htmlBody e-mail content with HTML tags
* #param mapInlineImages
* key: Content-ID
* value: path of the image file
* #throws AddressException
* #throws MessagingException
*/
public static void send(String host, String port,
final String userName, final String password, String toAddress,
String subject, String htmlBody,
Map<String, String> mapInlineImages)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlBody, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds inline image attachments
if (mapInlineImages != null && mapInlineImages.size() > 0) {
Set<String> setImageID = mapInlineImages.keySet();
for (String contentId : setImageID) {
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setHeader("Content-ID", "<" + contentId + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
String imageFilePath = mapInlineImages.get(contentId);
try {
imagePart.attachFile(imageFilePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(imagePart);
}
}
msg.setContent(multipart);
Transport.send(msg);
}
}
package net.codejava.mail;
import java.util.HashMap;
import java.util.Map;
/**
* This program tests out the EmbeddedImageEmailUtil utility class.
* #author www.codejava.net
*
*/
public class InlineImageEmailTester {
/**
* main entry of the program
*/
public static void main(String[] args) {
// SMTP info
String host = "smtp.gmail.com";
String port = "587";
String mailFrom = "YOUR_EMAIL";
String password = "YOUR_PASSWORD";
// message info
String mailTo = "YOUR_RECIPIENT";
String subject = "Test e-mail with inline images";
StringBuffer body
= new StringBuffer("<html>This message contains two inline images.<br>");
body.append("The first image is a chart:<br>");
body.append("<img src=\"cid:image1\" width=\"30%\" height=\"30%\" /><br>");
body.append("The second one is a cube:<br>");
body.append("<img src=\"cid:image2\" width=\"15%\" height=\"15%\" /><br>");
body.append("End of message.");
body.append("</html>");
// inline images
Map<String, String> inlineImages = new HashMap<String, String>();
inlineImages.put("image1", "E:/Test/chart.png");
inlineImages.put("image2", "E:/Test/cube.jpg");
try {
EmbeddedImageEmailUtil.send(host, port, mailFrom, password, mailTo,
subject, body.toString(), inlineImages);
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Could not send email.");
ex.printStackTrace();
}
}
}
Any comments will be very appreciated.
Problem solved.
I have to change:
new MimeMultipart();
to this:
new MimeMultipart("related");
I am working on Oracle MAF app and using Java mail API for sending outlook meeting requests. I can successfully send mail from java command-line, but when trying same using Mobile app, the code doesn't go after where creating "MimeMessage" class object.
MimeMessage message = new MimeMessage(mailSession);
printStackTrace() shows this exception:
06-09 10:54:43.146: D/JVM(16075): [SEVERE - oracle.adfmf.framework -
Utility - invoke] InvocationTargetException Error: ERROR
[oracle.adfmf.framework.exception.AdfException] - Error invoking
method 'sendMail' in 'class beans.UtilBean'
06-09 12:14:07.466: I/System.out(3760): [SEVERE -
oracle.adfmf.framework - adf.mf.internal - logError] Request:
{"classname":"oracle.adfmf.framework.api.Model","method":"processBatchRequests","params":[false,[{"classname":"oracle.adfmf.framework.api.Model","method":"evaluateMethodExpression","params":["#{UtilBean.sendMail}",[{".type":"oracle.adfmf.amx.event.ActionEvent"}],"void",["oracle.adfmf.amx.event.ActionEvent"]]}]]}
exception: {"message":"Error invoking method 'sendMail' in 'class
beans.UtilBean'",".exception":true,"severity":"ERROR",".type":"oracle.adfmf.framework.exception.AdfException"}
Full source code of my class is here:
package beans;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
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.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import oracle.adfmf.amx.event.ActionEvent;
public class Email {
private static final String SMTP_HOST_NAME = "mail_host_name";
private static final String SMTP_AUTH_USER = "smtp_user_id";
private static final String SMTP_AUTH_PWD = "smtp_auth_pass";
private static final String SMTP_AUTH_PORT = "smtp_port";
private static final String MAIL_FROM_ADDRESS = "from_addr";
private static final String RECEIPENT_1 = "receipent_1_addr";
private static final String RECEIPENT_2 = "receipent_2_addr";
public void sendEmail(ActionEvent actionEvent) {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", SMTP_AUTH_PORT);
Authenticator auth = new SMTPAuthenticator();
//Get the session object
Session mailSession = Session.getDefaultInstance(props, auth);
//compose message
try {
System.out.print("CALLED0"); //I can see this in Logcat Logs
MimeMessage message = new MimeMessage(mailSession); // Program stuck here
System.out.print("CALLED1");//I can not see this in Logcat Logs
message.addHeaderLine("method=REQUEST");
message.addHeaderLine("charset=UTF-8");
message.addHeaderLine("component=vevent");
message.setFrom(new InternetAddress(MAIL_FROM_ADDRESS));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(RECEIPENT_1));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(RECEIPENT_2));
message.setSubject("Outlook Meeting Request Using JavaMail");
StringBuffer sb = new StringBuffer();
StringBuffer buffer =
sb.append("BEGIN:VCALENDAR\n" + "PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN\n" +
"VERSION:2.0\n" + "METHOD:REQUEST\n" + "BEGIN:VEVENT\n" +
"ATTENDEE;CN=\"Attendee1\";ROLE=REQ-PARTICIPANT;MAILTO:attendee1#addendant.com\n" +
"ATTENDEE;CN=\"Attendee2\";ROLE=OPT-PARTICIPANT;MAILTO:attendee2#addendant.com\n" +
"ORGANIZER:MAILTO:org#org.com\n" + "DTSTART:20050406T073000Z\n" +
"DTEND:20050406T080000Z\n" + "LOCATION:conf\n" + "TRANSP:OPAQUE\n" + "SEQUENCE:0\n" +
"UID:040000008200E00074C5B7101A82E00800000000A0A742E5073AC5010000000000000000100\n" +
" 0000029606C073D82204AB6C77ACE6BC2FBE2\n" + "DTSTAMP:20050405T122004Z\n" +
"CATEGORIES:Meeting\n" + "DESCRIPTION:What are you doing?\n\n" + "SUMMARY:How are you?\n" +
"PRIORITY:5\n" + "CLASS:PUBLIC\n" + "BEGIN:VALARM\n" + "TRIGGER:PT1440M\n" +
"ACTION:DISPLAY\n" + "DESCRIPTION:Reminder\n" + "END:VALARM\n" + "END:VEVENT\n" +
"END:VCALENDAR\n");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
messageBodyPart.setHeader("Content-ID", "calendar_message");
messageBodyPart.setContent(buffer.toString(), "text/calendar");
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
//send message
Transport.send(message);
System.out.println("message sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}
In Email class I added print statement before and after where creating "MimeMessage" class object, I am able to see first print in logcat but not second.
Deploying java project on Web logic server as a web service (as a .war package) worked for me.
I am sending mails from my application using JAVA mail on smtp server, port 465. My need is that, I have to set Message-ID before sending mail. I did some R&D and found the code below. I had override the method updateMessageID() of MimeMessage
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
public class CustomMimeMessage extends MimeMessage {
public CustomMimeMessage(Session session) {
super(session);
}
#Override
protected void updateMessageID() throws MessagingException {
setHeader("Message-ID", "message id");
}
}
And then I had made an instance of CustomMimeMessage in my service and then invoke updateMessageID() method using that instance, but I still get the Message-ID generated by gmail.
In your code
setHeader("Message-ID", "message id");
you are trying to set "message id" as Message-ID which is quite wrong you have to set a unique id that qualify all the rules of the message id (Read This).
Try this..,.
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class CustomMimeMessage extends MimeMessage {
Session session;
private static int id = 0;
public CustomMimeMessage(Session session) {
super(session);
this.session=session;
}
#Override
protected void updateMessageID() throws MessagingException {
setHeader("Message-ID", "<" + getUniqueMessageIDValue(session) + ">");
}
public static String getUniqueMessageIDValue(Session ssn) {
String suffix = null;
InternetAddress addr = InternetAddress.getLocalAddress(ssn);
if (addr != null)
suffix = addr.getAddress();
else {
suffix = "javamailuser#localhost"; // worst-case default
}
StringBuffer s = new StringBuffer();
// Unique string is <hashcode>.<id>.<currentTime>.JavaMail.<suffix>
s.append(s.hashCode()).append('.').append(getUniqueId()).append('.').
append(System.currentTimeMillis()).append('.').
append("JavaMail.").
append(suffix);
return s.toString();
}
private static synchronized int getUniqueId() {
return id++;
}
}
I am doing something similar but sending from the local host instead. This Might help.
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.Transport;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
public class SendEmail {
/**
* Sends an email based on paramaters passed to it.
*
* #param toWho - the recipiants email address
* #param fromWho - the senders email address
* #param subject - the subject line of the email
* #param body - the email message body
* #return void
* #throws AddressException
* #throws MessageingException
*/
public void sendMail(String toWho, String subject, String body, String fromWho) throws AddressException, MessagingException {
// Setting Properties
Properties props = System.getProperties();
props.put("mail.imaps.ssl.trust", "*"); // trusting all server certificates
props.setProperty("mail.store.protocol", "imaps");
// Get the default Session object.
Session session = Session.getDefaultInstance(props, null);
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From header
message.setFrom(new InternetAddress(fromWho));
// Set to header
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toWho));
// Header set subject
message.setSubject(subject);
// Message Body
message.setContent(body, "text/html; charset=utf-8");
// Send message
Transport.send(message);
}
}
You can set message-id to MimeMessage before call Transport.send() by extending MimeMessage like this.
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
public class MyMimeMessage extends MimeMessage {
public MailorMimeMessage(Session session) {
super(session);
}
#Override
protected void updateMessageID() throws MessagingException {
if (getHeader("Message-Id") == null) {
super.updateMessageID();
}
}
}
And set custom message-id.
message.setHeader("Message-Id","<MY-MESSAGE-ID>");
You can try custom id with .(dot) before left side of '#'. It worked for me.
Check the following code snippet:
public class CustomMimeMessage extends MimeMessage {
Session session;
private static int id = 0;
public CustomMimeMessage(Session session) {
super(session);
this.session = session;
}
protected void updateMessageID() throws MessagingException {
debugLog("Calling updateMessageID()");
setHeader("Message-ID", "<" + getUniqueMessageIDValue(session) + ">");
}
public static String getUniqueMessageIDValue(Session ssn) {
String suffix = null;
InternetAddress addr = InternetAddress.getLocalAddress(ssn);
if (addr != null) {
testLog("InternetAddress = " + addr.toString());
String address = addr.getAddress();
if (address.contains("#")) {
address = address.substring(address.lastIndexOf("#"), address.length());
suffix = address;
}
}
if (suffix == null) {
suffix = "#mail";// worst-case default
}
testLog("suffix Address = " + suffix);
StringBuffer s = new StringBuffer();
s.append(System.currentTimeMillis()).append("")
.append(getUniqueId()).append(suffix).append(".sm");
testLog("NEW MESSAGE-ID: " + s.toString());
return s.toString();
}
private static synchronized int getUniqueId() {
return id++;
}
For more details, Please refer the following RFC's. These are really helpful for creating syntax for Custom message-id.
RFC 2822
RFC 5322
Hope this would also work for you.
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]");