please help me work this code:
package com.ibm.lims;
import java.security.Security;
import java.util.Properties;
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;
public class mails {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_PORT = "465";
private static final String emailMsgTxt = "robin borrowed a book";
private static final String emailSubjectTxt = "online library management system notification";
private static final String emailFromAddress = "robins.lims2009#gmail.com";
private static final String SSL_FACTORY ="javax.net.ssl.SSLSocketFactory";
private static final String[] sendTo = {"robins.lims2009#gmail.com","supersmartrobin#yahoo.co.in"};
public static void mailer() throws Exception{
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
new mails().sendSSLMessage(sendTo,emailSubjectTxt,emailMsgTxt,emailFromAddress);
System.out.println("Sucessfully Sent mail to All Users");
}
public void sendSSLMessage(String recipients[],String subject,String message,String from) throws MessagingException {
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol","smtps");
Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("robins.lims2009#gmail.com","xxxxxxxxx");
}
}
);
MimeMessage message1 =new MimeMessage(session);
message1.setFrom(new InternetAddress(from));
for(int i=0;i<recipients.length;i++){
message1.addRecipient(Message.RecipientType.TO,new InternetAddress(recipients[i]));
}
message1.setSubject(subject);
MimeBodyPart messageBodyPart =new MimeBodyPart();
messageBodyPart.setText(message);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
message1.setContent(multipart);
Transport.send( message1 );
}
}
i am getting send failred exceptions as:
Loading javamail.default.providers from jar:file:/C:/Program Files/IBM/WebSphere/AppServerCommunityEdition/repository/org/apache/geronimo/javamail/geronimo-javamail_1.4_mail/1.7/geronimo-javamail_1.4_mail-1.7.jar!/META-INF/javamail.default.providers
DEBUG: loading new provider protocol=smtp, className=org.apache.geronimo.javamail.transport.smtp.SMTPTransport, vendor=Apache Software Foundation, version=1.0
DEBUG: loading new provider protocol=smtps, className=org.apache.geronimo.javamail.transport.smtp.SMTPSTransport, vendor=Apache Software Foundation, version=1.0
DEBUG: loading new provider protocol=nntp-post, className=org.apache.geronimo.javamail.transport.nntp.NNTPTransport, vendor=Apache Software Foundation, version=1.0
DEBUG: loading new provider protocol=nntp-posts, className=org.apache.geronimo.javamail.transport.nntp.NNTPSSLTransport, vendor=Apache Software Foundation, version=1.0
DEBUG: loading new provider protocol=nntp, className=org.apache.geronimo.javamail.store.nntp.NNTPStore, vendor=Apache Software Foundation, version=1.0
DEBUG: loading new provider protocol=nntps, className=org.apache.geronimo.javamail.store.nntp.NNTPSSLStore, vendor=Apache Software Foundation, version=1.0
DEBUG: loading new provider protocol=pop3, className=org.apache.geronimo.javamail.store.pop3.POP3Store, vendor=Apache Software Foundation, version=1.0
DEBUG: loading new provider protocol=pop3s, className=org.apache.geronimo.javamail.store.pop3.POP3SSLStore, vendor=Apache Software Foundation, version=1.0
DEBUG: loading new provider protocol=imap, className=org.apache.geronimo.javamail.store.imap.IMAPStore, vendor=Apache Software Foundation, version=1.0
DEBUG: loading new provider protocol=imaps, className=org.apache.geronimo.javamail.store.imap.IMAPSSLStore, vendor=Apache Software Foundation, version=1.0
DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type#17858a9; class=org.apache.geronimo.javamail.transport.smtp.SMTPTransport; vendor=Apache Software Foundation;version=1.0
DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type#17858a9; class=org.apache.geronimo.javamail.transport.smtp.SMTPTransport; vendor=Apache Software Foundation;version=1.0
smtp DEBUG: Failing connection for missing authentication information
smtp DEBUG: Attempting plain socket connection to server smtp.gmail.com:465
220 mx.google.com ESMTP 20sm19490287pzk.13
EHLO smartrobin
250-mx.google.com at your service, [121.242.109.66]
250-SIZE 35651584
250-8BITMIME
250-AUTH LOGIN PLAIN
250-ENHANCEDSTATUSCODES
250 PIPELINING
smtp DEBUG: Processing extension SIZE 35651584
smtp DEBUG: Processing extension 8BITMIME
smtp DEBUG: Processing extension AUTH LOGIN PLAIN
smtp DEBUG: Processing extension ENHANCEDSTATUSCODES
smtp DEBUG: Processing extension PIPELINING
QUIT
221 2.0.0 closing connection 20sm19490287pzk.13
smtp DEBUG: Failing connection for missing authentication information
smtp DEBUG: Attempting plain socket connection to server smtp.gmail.com:465
220 mx.google.com ESMTP 23sm19555940pzk.4
EHLO smartrobin
250-mx.google.com at your service, [121.242.109.66]
250-SIZE 35651584
250-8BITMIME
250-AUTH LOGIN PLAIN
250-ENHANCEDSTATUSCODES
250 PIPELINING
smtp DEBUG: Processing extension SIZE 35651584
smtp DEBUG: Processing extension 8BITMIME
smtp DEBUG: Processing extension AUTH LOGIN PLAIN
smtp DEBUG: Processing extension ENHANCEDSTATUSCODES
smtp DEBUG: Processing extension PIPELINING
QUIT
221 2.0.0 closing connection 23sm19555940pzk.4
2010-01-09 17:08:49,046 ERROR [[jsp]] Servlet.service() for servlet jsp threw exception
javax.mail.MessagingException: Server doesn't support required transport level security
at org.apache.geronimo.javamail.transport.smtp.SMTPConnection.sendHandshake(SMTPConnection.java:821)
at org.apache.geronimo.javamail.transport.smtp.SMTPConnection.protocolConnect(SMTPConnection.java:159)
at org.apache.geronimo.javamail.transport.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:165)
at javax.mail.Service.connect(Service.java:271)
at javax.mail.Service.connect(Service.java:91)
at javax.mail.Service.connect(Service.java:76)
at javax.mail.Transport.send(Transport.java:94)
at javax.mail.Transport.send(Transport.java:48)
at com.ibm.lims.mails.sendSSLMessage(mails.java:86)
at com.ibm.lims.mails.mailer(mails.java:35)
at org.apache.jsp.borrow_jsp._jspService(borrow_jsp.java:142)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.geronimo.tomcat.valve.DefaultSubjectValve.invoke(DefaultSubjectValve.java:56)
at org.apache.geronimo.tomcat.GeronimoStandardContext$SystemMethodValve.invoke(GeronimoStandardContext.java:406)
at org.apache.geronimo.tomcat.valve.GeronimoBeforeAfterValve.invoke(GeronimoBeforeAfterValve.java:47)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:567)
at org.apache.geronimo.tomcat.valve.ThreadCleanerValve.invoke(ThreadCleanerValve.java:40)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Unknown Source)
It seems like your authentication credentials aren't working. Does it work if you try setting your username/password directly in the connect line? For instance:
Transport transport = session.getTransport("smtp");
transport.connect(SMTP_HOST_NAME, "robins.lims2009#gmail.com","xxxxxxxxx");
transport.sendMessage(message1, message1.getAllRecipients());
transport.close();
Related
I'm trying to run an Example of test scripts coded with java in Eclipse with Appium. I run Appium by npm (i'm using Appium 1.6.3, i'm not new to Appium i run it before on Mac and on windows without any problem but this time in Ubuntu it looks a bit different while it's not with the appium application but with console)
appium --address 127.0.0.1
I'm using
java-client-4.1.2.jar
selenium-java-3.0.1.jar
selenium-server-standalone-3.0.1.jar
testng-6.9.10.jar
And my java class is :
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class FirstTest {
AndroidDriver<AndroidElement> driver;
File path = new File("/home/emna/Téléchargements/AutomationFiles/app-release.apk");
#BeforeClass
public void setUp() throws MalformedURLException {
System.out.println("app Dir.--->" + path);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "SM-G360H");
capabilities.setCapability("version", "4.4.4");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("platformVersion", "platform");
capabilities.setCapability("udid", "***************");
capabilities.setCapability("app", path.getAbsolutePath());
capabilities.setCapability("appPackage", "com.bulldozer.gaa");
capabilities.setCapability("appActivity",
"com.bulldozer.gaa.activities.MainActivity");
driver = new AndroidDriver<AndroidElement>(new URL("http://127.0.0.1:4723/wd/hub"),
capabilities);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
#Test
public void Test1() throws InterruptedException {
// driver.wait(10000);
System.out.println("GAA");
driver.findElement(By.id("acceptCheckbox")).click();
driver.findElement(By.id("continueBtn")).click();
}
#AfterClass
public void tearDown() {
driver.quit();
}
}
But the problem is that :
[TestNG] Running:
/tmp/testng-eclipse--2049046107/testng-customsuite.xml
app Dir.--->/home/emna/Téléchargements/AutomationFiles/app-release.apk
Jan 24, 2017 1:14:44 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
Jan 24, 2017 1:14:59 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Falling back to original OSS JSON Wire Protocol.
Jan 24, 2017 1:15:10 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Falling back to straight W3C remote end connection
FAILED CONFIGURATION: #BeforeClass setUp
org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{app=/home/emna/Téléchargements/AutomationFiles/app-release.apk, appPackage=com.bulldozer.gaa, appActivity=com.bulldozer.gaa.activities.MainActivity, platformVersion=platform, platformName=Android, udid=*************, deviceName=SM-G360H, version=4.4.4}], required capabilities = Capabilities [{}]
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:48:19 -0700'
System info: host: 'tarek-Vostro-3902', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-59-generic', java.version: '1.8.0_91'
Driver info: driver.version: AndroidDriver
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:91)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:141)
at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:69)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:40)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
Here the Appium log file :
[debug] [ADB] Running '/home/emna/Android/Sdk/platform-tools/adb' with args: ["-P",5037,"-s","***************","shell","am","force-stop","io.appium.unlock"]
[debug] [Logcat] Stopping logcat capture
[debug] [AndroidDriver] Not cleaning generated files. Add `clearSystemFiles` capability if wanted.
[MJSONWP] Encountered internal error running command: Error: Error occured while starting App. Original error: Permission to start activity denied.
at Object.wrappedLogger.errorAndThrow (lib/logger.js:60:13)
at ADB.callee$0$0$ (../../../lib/tools/apk-utils.js:80:9)
at tryCatch (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:67:40)
at GeneratorFunctionPrototype.invoke [as _invoke] (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:315:22)
at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:100:21)
at GeneratorFunctionPrototype.invoke (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:136:37)
at process._tickCallback (internal/process/next_tick.js:103:7)
[HTTP] <-- POST /wd/hub/session 500 11015 ms - 223
[HTTP] --> POST /wd/hub/session {"capabilities":{"desiredCapabilities":{"app":"/home/emna/Téléchargements/AutomationFiles/app-release.apk","appPackage":"com.bulldozer.gaa","appActivity":"com.bulldozer.gaa.activities.MainActivity","platformVersion":"platform","platformName":"Android","udid":"************","deviceName":"SM-G360H","version":"4.4.4"},"requiredCapabilities":{}}}
[debug] [MJSONWP] Bad parameters: BadParametersError: Parameters were incorrect. We wanted {"required":["desiredCapabilities"],"optional":["requiredCapabilities","capabilities","sessionId","id","sessionId","id","sessionId","id"]} and you sent ["capabilities"]
[HTTP] <-- POST /wd/hub/session 400 5 ms - 205
You forgot the most important capability, which is the path to the .apk:
capabilities.setCapability("app", "appPath");
Also, i would recommend on changing from RemoteWebDriver to Android driver, since you will have some more functionality:
driver = new AndroidDriver(....)
ps: you can update your java-client to 4.1.2 and testng to 6.9.10
The reason is because your Appium is running already the app using GUI settings.
Simultaneously you are trying to run it again from your code.
What should help : In Appium UI go to Android settings (basic)
Application panel: do not define / launch the app and its activities.
Capabilities panel: define and select {Platform Name, Automation Name, Platform Version}
The problem is with the apk file itself, I used an other .apk file with the same configuration i have used and it works fine !
This could be an issue, since as I understood you are running Appium on the same machine where your client scripts reside, try using "http://127.0.1.1:4723/wd/hub" instead. this Solution works for me
AndroidDriver<AndroidElement> driver = null;
driver = new AndroidDriver<>(new URL("http://127.0.1.1:4723/wd/hub"), capabilities);
I just started to learn Selenium WebDriver. Could you all help me to resolve below problem.
I simply want to open the web-site(I am able to open browser successfully but navigation got failed )
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class webdriverdemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
//Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch website
driver.navigate().to("http://www.calculator.net/");
//Maximize the browser
driver.manage().window().maximize();
}
}
I found below errors :
Exception in thread "main"
org.openqa.selenium.remote.UnreachableBrowserException: Could not
start a new session. Possible causes are invalid address of the remote
server or browser start-up failure.
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
System info: host: 'WIN-EHSO6G1D9KD', ip: '192.168.13.2', os.name: 'Windows Server 2012', os.arch: 'amd64', os.version: '6.2',
java.version: '1.8.0_91'
Driver info: driver.version: FirefoxDriver
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:665)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:131)
at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:218)
at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:211)
at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:207)
at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:120)
at webdriverdemo.main(webdriverdemo.java:13)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:139)
at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:155)
at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:284)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:140)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:261)
at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:165)
at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:167)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:272)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:124)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:271)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
at org.openqa.selenium.remote.internal.ApacheHttpClient.fallBackExecute(ApacheHttpClient.java:144)
at org.openqa.selenium.remote.internal.ApacheHttpClient.execute(ApacheHttpClient.java:90)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.execute(NewProfileExtensionConnection.java:160)
at org.openqa.selenium.firefox.FirefoxDriver$LazyCommandExecutor.execute(FirefoxDriver.java:380)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:644)
... 7 more
Firefox version 47.0.6
Platform Win2k12 r2
Seems like there is some issue with creating session with Firefox.
Try the following code and test using Chrome browser.
You need to download the executable driver from: https://sites.google.com/a/chromium.org/chromedriver/downloads
public static void main(String[] args){
System.setProperty("webdriver.chrome.driver","/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver = new ChromeDriver();
//Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch website
driver.get("http://www.calculator.net/");
//Maximize the browser
driver.manage().window().maximize();
}
I created an example to send emails using STARTLS. Running it on 3 different windows versions hosted in different domains, everything works.
The bizzare thing is that when I run it on a Ubuntu Server 14.02 LTS it doesn't works. There is no firewall blocking and the java application binaries are the same.
This is the code:
// Port we will connect to on the Amazon SES SMTP endpoint. We are choosing port 25 because we will use
// STARTTLS to encrypt the connection.
static final int PORT = 25;
public static void main(String[] args) throws Exception {
// Create a Properties object to contain connection configuration information.
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", PORT);
// Set properties indicating that we want to use STARTTLS to encrypt the connection.
// The SMTP session will begin on an unencrypted connection, and then the client
// will issue a STARTTLS command to upgrade to an encrypted connection.
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.ssl.enable", "false");
props.put("mail.debug", "true");
// Create a Session object to represent a mail session with the specified properties.
Session session = Session.getDefaultInstance(props);
// Create a message with the specified information.
MimeMessage msg = new MimeMessage(session);
msg.setReplyTo(InternetAddress.parse("no-reply#no-host.com"));
msg.setFrom(new InternetAddress(FROM));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
msg.setSubject(SUBJECT);
msg.setContent(BODY, "html/plain");
// Create a transport.
Transport transport = session.getTransport("smtp");
// Send the message.
try {
System.out.println("Attempting to send an email through the Amazon SES SMTP interface...");
// Connect to Amazon SES using the SMTP username and password you specified above.
transport.connect(HOST, PORT, SMTP_USERNAME, SMTP_PASSWORD);
// Send the email.
transport.sendMessage(msg, msg.getAllRecipients());
System.out.println("Email sent!");
} catch (Exception ex) {
System.out.println("The email was not sent.");
System.out.println("Error message: " + ex.getMessage());
} finally {
// Close and terminate the connection.
transport.close();
}
}
This is the javamail log from a Windows environment (what is working):
DEBUG: JavaMail version 1.5.4
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
Attempting to send an email through the Amazon SES SMTP interface...
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "email-smtp.us-west-2.amazonaws.com", port 25, isSSL false
220 email-smtp.amazonaws.com ESMTP SimpleEmailService-1207632523 H3nxFSQJ7ktEpHBHuT38
DEBUG SMTP: connected to host "email-smtp.us-west-2.amazonaws.com", port: 25
EHLO roberton
250-email-smtp.amazonaws.com
250-8BITMIME
250-SIZE 10485760
250-STARTTLS
250-AUTH PLAIN LOGIN
250 Ok
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "SIZE", arg "10485760"
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN"
DEBUG SMTP: Found extension "Ok", arg ""
STARTTLS
220 Ready to start TLS
EHLO xxxxxxxxxxxxxxxx
250-email-smtp.amazonaws.com
250-8BITMIME
250-SIZE 10485760
250-STARTTLS
250-AUTH PLAIN LOGIN
250 Ok
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "SIZE", arg "10485760"
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN"
DEBUG SMTP: Found extension "Ok", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<naoresponder#xxxxxxxxx>
250 Ok
RCPT TO:<xxxxxxxxxxxxxxxxxxxxx>
250 Ok
DEBUG SMTP: Verified Addresses
DEBUG SMTP: xxxxxxxxxxxxxxx
DATA
354 End data with <CR><LF>.<CR><LF>
From: xxxxxxxxxxxxxx
Reply-To: xxxxxxxxxxxxx
To: xxxxxxxxxxxxxxxxxxx
Message-ID: <1926764753.0.1448359358140#xxxxxxxx>
Subject: Amazon SES test (SMTP interface accessed using Java)
MIME-Version: 1.0
Content-Type: html/plain
Content-Transfer-Encoding: 7bit
This email was sent through the Amazon SES SMTP interface by using Java.
.
250 Ok 0000015138f203b5-6fcd5424-60c3-43eb-9542-83699cf36c46-000000
DEBUG SMTP: message successfully delivered to mail server
Email sent!
QUIT
221 Bye
And this is the log from the Ubuntu (environment what isn't working):
DEBUG: JavaMail version 1.5.4
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
Attempting to send an email through the Amazon SES SMTP interface...
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "email-smtp.us-west-2.amazonaws.com", port 25, isSSL false
220 email-smtp.amazonaws.com ESMTP SimpleEmailService-1207632523 tIUsmWGoY4gXLCMWdUpi
DEBUG SMTP: connected to host "email-smtp.us-west-2.amazonaws.com", port: 25
EHLO xxxxxxxxx
250-email-smtp.amazonaws.com
250-8BITMIME
250-SIZE 10485760
250-AUTH PLAIN LOGIN
250 Ok
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "SIZE", arg "10485760"
DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN"
DEBUG SMTP: Found extension "Ok", arg ""
DEBUG SMTP: STARTTLS required but not supported
The email was not sent.
Error message: STARTTLS is required but host does not support STARTTLS
This is the callstack error:
javax.mail.MessagingException: STARTTLS is required but host does not support STARTTLS
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:719)
at javax.mail.Service.connect(Service.java:364)
at SESEmail.main(SESEmail.java:64)
Java version: 1.8.0_60-b27
Why this is happening?
I was using an official example from AWS SES http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-smtp-java.html , and this one was using port smtp 25 for TLS.
For some reason, this port (25) doesn't works with TLS in some of my enviroments.
After some research, I found this http://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-connect.html and tried to use the default TLS port 587, and now it works in both of my environments (linux and windows).
I think this was a problem/behavior from AWS SES servers and not a Java Mail problem. I will try to report this for AWS team.
I'm trying to implement a service on App Engine that interacts with an Gmail account using OAuth2, Java 7 and App Engine SDK 1.8.2. The problem being encountered is via the use of sample code provided by https://code.google.com/p/google-mail-oauth2-tools/wiki/JavaSampleCode the Security provider does not appear to be detected on a node although works locally fine. The code provided by the link before has been modified to be initiated by a servlet with sample code:
import java.io.IOException;
import java.security.Provider;
import java.security.Security;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.URLName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.code.samples.oauth2.OAuth2SaslClientFactory;
import com.sun.mail.imap.IMAPSSLStore;
import com.sun.mail.imap.IMAPStore;
import com.sun.mail.smtp.SMTPTransport;
public class RunnerServlet extends HttpServlet
{
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
String email = request.getParameter( "email");
String oauthToken = request.getParameter( "oauthToken");
initialize();
try
{
IMAPStore imapStore = connectToImap("imap.gmail.com",
993,
email,
oauthToken,
true);
System.out.println("Successfully authenticated to IMAP.\n");
SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com",
587,
email,
oauthToken,
true);
System.out.println("Successfully authenticated to SMTP.");
}
catch( Exception e )
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
throw new RuntimeException( e );
}
}
public static final class OAuth2Provider extends Provider {
private static final long serialVersionUID = 1L;
public OAuth2Provider() {
super("Google OAuth2 Provider", 1.0,
"Provides the XOAUTH2 SASL Mechanism");
put("SaslClientFactory.XOAUTH2",
"com.google.code.samples.oauth2.OAuth2SaslClientFactory");
}
}
public static void initialize() {
Security.addProvider(new OAuth2Provider());
}
public static IMAPStore connectToImap(String host, int port,
String userEmail, String oauthToken, boolean debug)
throws Exception {
Properties props = new Properties();
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
Session session = Session.getInstance(props);
session.setDebug(debug);
session.getProperties().put("mail.imaps.sasl.enable", "true");
session.getProperties().put("mail.imaps.sasl.mechanisms", "XOAUTH2");
session.getProperties().put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
final URLName unusedUrlName = null;
IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
final String emptyPassword = "";
store.connect(host, port, userEmail, emptyPassword);
return store;
}
public static SMTPTransport connectToSmtp(String host, int port,
String userEmail, String oauthToken, boolean debug)
throws Exception {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "true");
props.put("mail.smtp.sasl.mechanisms", "XOAUTH2");
props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
Session session = Session.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
final String emptyPassword = null;
transport.connect(host, port, userEmail, emptyPassword);
return transport;
}
}
The IMAP debug trace is:
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: enable SASL
DEBUG IMAPS: SASL mechanisms allowed: XOAUTH2
DEBUG IMAPS: trying to connect to host "imap.gmail.com", port 993, isSSL true
* OK Gimap ready for requests from xxx.xxx.xxx.xxx ZZZZZZZZZ
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY
A0 OK Thats all she wrote! ZZZZZZZZZ
DEBUG IMAPS: AUTH: XOAUTH
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=imap.gmail.com, user=som...#gmail.com, password=<non-null>
DEBUG IMAPS: SASL authentication command trace suppressed
DEBUG IMAPS: SASL Mechanisms:
DEBUG IMAPS: XOAUTH2
DEBUG IMAPS:
DEBUG IMAPS: No SASL support
DEBUG IMAPS: SASL authentication failed
DEBUG IMAPS: LOGIN command trace suppressed
DEBUG IMAPS: LOGIN command result: A1 NO Empty username or password. ZZZZZZZZZ
DEBUG IMAPS: trying to connect to host "imap.gmail.com", port 993, isSSL true
* OK Gimap ready for requests from xxx.xxx.xxx.xxx YYYYYYYYYY
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH AUTH=XOAUTH2
A0 OK Thats all she wrote! YYY
DEBUG IMAPS: AUTH: XOAUTH
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=imap.gmail.com, user=som...#gmail.com, password=<non-null>
DEBUG IMAPS: SASL authentication command trace suppressed
DEBUG IMAPS: SASL Mechanisms:
DEBUG IMAPS: XOAUTH2
DEBUG IMAPS:
DEBUG IMAPS: No SASL support
DEBUG IMAPS: SASL authentication failed
DEBUG IMAPS: LOGIN command trace suppressed
DEBUG IMAPS: LOGIN command result: A1 NO Empty username or password. YYYYYYYYYY
java.lang.RuntimeException: javax.mail.AuthenticationFailedException: Empty username or password. YYYYYYYYYY
This problem only occurs on a deployed node. Ensured that the provider was correct path and installed and using the latest versions of App Engine SDK that facilitates the IMAP and SMTP sockets. Triggering has been attempted via sample servlet and task on task queue.
Thank you for assistance in advance.
I've the same problem than you...
I've been researching, and I think the session isn't instantiated correctly. I attached a picture that shows the difference.
At the top of the image shows the contents of the variable "props" which is the same values for the AppEngine project (left image) that the project Normal(right image).
The down images shows the contents of the Session variable, and within this, the contents of the variables Properties. Like you can see in the left case, is null. But in the right case have values.
Here is the image: http://ricorrico.comoj.com/misc/img2.jpg
It really is a bug, is there any workaround?
Thank you very much in advance.
Regards!
Not sure if you are still running into this issue, but #user2606850 was very close to the solution. Initializing the session with the properties set does not properly initialize the session.
BUT adding the right properties AFTER the Session is created, WORKS !
Properties props = new Properties();
Session session = Session.getInstance(props);
props = session.getProperties();
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
...
Tested an proven to work deployed to AppEngine.
i am developing a simple web application using mail, with MyEclipse8.0.1 and Weblogic8.0 as server. Following is my code for sending email,it works well for console but when i m running it with myeclipse and Weblogic,it shows following error:
javax.mail.SendFailedException: Sending failed; nested exception is: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465
Here is my Code in jsp:
<%
try {
Properties p = new Properties();
p.put("mail.transport.protocol","smtp");
p.put("mail.smtp.host","smtp.gmail.com");
p.put("mail.smtp.port","465");
p.put("mail.smtp.auth","true");
p.put("mail.smtp.debug","true");
p.put("mail.smtp.starttls.enable", "true");
p.put("mail.smtp.ssl.enable", "true");
p.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
p.put("mail.smtp.socketFactory.port", "465");
p.put("mail.smtp.socketFactory.fallback", "false");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session s = Session.getInstance(p,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user","pass");}});
Message msg = new MimeMessage(s);
msg.setFrom(new InternetAddress("toaddr#gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("toAddr#gmail.com"));
msg.setSentDate(new java.util.Date());
msg.setSubject("MySub");
msg.setText("Body");
Transport.send(msg);
out.println("Mail sent successfully");
}
catch (Exception e)
{
//e.printStackTrace();
System.out.println("Exception : " + e);
out.println("Exception : " + e);
}
%>
One Interesting thing happened here is when i tried same code by starting MyEclipse Tomcat server and run the code, it send successfully to my gmail account as it was working from console program. but again when i tried above code with Weblogic 8.0, it showed me exception "javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465 ".
I dont know what is going wrong, whether in the code or some special setting in server. So please please experts, guide me.
Thanks a ton, in advance.
The JavaMail FAQ has tips for debugging connection problems.
Are Tomcat and WebLogic running on the same machine? Possibly there's a firewall or anti-virus product preventing you from connecting.