Javamail Configuration clarification - jakarta-mail

Through my application using Javamail API if I want to send email between any two external email addresses say gmail->yahoo or yahoo->gmail or any other email account without using authentication mechanism how should I configure mail.smtp.host property?
What is the correct way of configuring javamail properties for sending emails between any two external email addresses ?
Sample code to send mail is given below:
Session session = Session.getDefaultInstance(new Properties(),null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("test#gmail.com"));
InternetAddress[] toAddress = {new InternetAddress("test#yahoo.com")};
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("test mail"); message.setText("test body");
Transport.send(message);

Most public mail servers require authentication. If you want to do it without authentication, you'll need to run your own mail server.

This is for gmail, try it. You need mail.jar
public static void main(String[] args) {
final String username = "yourId#gmail.com";
final String password = "your-pwd";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("yourId#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("some-mail#gmail.com"));
message.setSubject("A Mail Subject");
message.setText("Hey I'm sending mail using java api");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
Edit :
Link to download Java mail Api along with mail.jar

Related

Unable to capture browser network logs with BrowserStack local, BrowserMobProxy embedded mode and Selenium 3.x using java

Below is the dependencies in my maven pom.xml
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.14.0</version>
<groupId>net.lightbody.bmp</groupId>
<artifactId>[browsermob-core][1]</artifactId>
<version>2.1.5</version>
<groupId>com.browserstack</groupId>
<artifactId>[browserstack-local-java][1]</artifactId>
<version>1.0.3</version>
Below is the code which I'm using to initiate the BrowserMobProxy.
private static void browserMobSeleniumProxyStart() {
try {
proxy = new BrowserMobProxyServer();
proxy.setTrustAllServers(true);
proxy.chainedProxyAuthorization(
System.getProperty("proxy.user"), System.getProperty("proxy.pass"), AuthType.BASIC);
proxy.setChainedProxy(new InetSocketAddress(httpProxyHost, Integer.parseInt(httpProxyPort)));
// Enable HAR.
proxy.enableHarCaptureTypes(
EnumSet.of(
CaptureType.REQUEST_HEADERS,
CaptureType.REQUEST_CONTENT,
CaptureType.RESPONSE_CONTENT,
CaptureType.RESPONSE_HEADERS
)
);
proxy.start(browserLocalProxyPort);
localHostAddress = Inet4Address.getLocalHost().getHostAddress();
localHostPort = String.valueOf(proxy.getPort());
} catch (Exception e) {
proxy.stop();
e.printStackTrace();
}
Variables httpProxyHost and httpProxyPort are the corporateProxy IP and Port.
Below is the code to initiate the BrowserStack-local
private static void browserStackLocalStart() {
bsLocal = new Local();
bsLocalArgs = new HashMap<>();
bsLocalArgs.put("key", AUTOMATE_ACCESS_KEY);
// BrowserStack local executable.
bsLocalArgs.put("binarypath", format(BROWSERSTACK_PATH, "/src/test/resources/BrowserStackLocal"));
// Force to use local and Corp proxy.
bsLocalArgs.put("forcelocal", "true");
bsLocalArgs.put("forceproxy", "true");
// Set Corp Proxy and user crendentials.
bsLocalArgs.put("proxyHost", httpProxyHost);
bsLocalArgs.put("proxyPort", httpProxyPort);
bsLocalArgs.put("proxyUser", System.getProperty("proxy.user"));
bsLocalArgs.put("proxyPass", System.getProperty("proxy.password"));
// Set local Proxy to BrowserMobProxy host - localhost ip and port and set user credentials.
bsLocalArgs.put("localProxyHost", localHostAddress);
bsLocalArgs.put("localProxyPort", localHostPort);
bsLocalArgs.put("-localProxyUser", System.getProperty("proxy.user"));
bsLocalArgs.put("-localProxyPass", System.getProperty("proxy.password"));
seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
try {
if(bsLocal.isRunning()) bsLocal.stop(bsLocalArgs);
bsLocal.start(bsLocalArgs);
log.info(format("Browser Stack Local status: %s", bsLocal.isRunning()));
} catch (Exception e) {
log.warning("!!! Cannot start browserstack local !!!");
}
}
Below is method to initiate the driver on BrowserStack
private static void setDriverWithBrowserstackOptions() {
// Start BrowserMob proxy and browserstack-local.
browserMobSeleniumProxyStart();
browserStackLocalStart();
String jobName = System.getenv("JOB_BASE_NAME");
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserstack.local", "true");
caps.setCapability("browserstack.selenium_version", "3.14.0");
caps.setCapability("browserstack.debug","true");
caps.setCapability("browserstack.networkLogs","false");
caps.setCapability("acceptSslCerts", "true");
caps.setCapability("name", testName);
caps.setCapability("project", "SampleProj");
caps.setCapability("sessionName", "sessionName1");
caps.setCapability("localIdentifier", "Local Test");
caps.setCapability("build", "Local");
caps.setCapability("browserstack.maskCommands", "setValues, getValues, setCookies, getCookies");
caps.setCapability(CapabilityType.PROXY, seleniumProxy);
// Chrome Options.
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
caps.merge(ChromeOptions.CAPABILITY, options);
URL url = null;
try {
url = new URL(URL);
} catch (MalformedURLException e) {
log.warning("Browserstack URL may be incorrect."+ URL);
}
// Initiate RemoteWebDriver instanc
WebDriver d = new RemoteWebDriver(url, caps);
// Create new HAR.
proxy.newHar();
try {
d.get("https://google.com");
Thread.sleep(10000);
// Fetch Har entries.
List<HarEntry> harEntries = proxy.getHar().getLog().getEntries();
for (HarEntry h : harEntries) {
System.out.println("---------------- HAR Request -----------------");
System.out.println(h.getRequest());
System.out.println("----------------------------------------------");
System.out.println("---------------- HAR Response -----------------");
System.out.println(h.getResponse());
System.out.println("----------------------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
}
}
I tried with and without BrowserMobProxy setChainedProxy but had no luck to capture the HAR entries.
Any thoughts and comments are appreciated.
You just have to set the following capability to capture the network logs on BrowserStack:
caps.setCapability("browserstack.networkLogs","true");
Also, you can capture the contents of the requests made using browserstack.networkLogsOptions. More details on https://www.browserstack.com/automate/capabilities

How to write send email test case and read Excel file test case in Selenium

Here is my my code to write a sample send email test case. When running the code email is not getting triggered. Please find attached data for more details
Login User details
Invalid User Details
Booking Data
Can anyone please help to resolve the issue as I am novice in selenium automation testing. Below is sample code of my Java code for configuration and triggering of email.
How to send out an Email notification in Selenium webdriver using Java, whenever some scenario is failed/passed in between?
public class SendEmail {
public SendEmail() {
}
public void email() {
// Create object of Property file
Properties props = new Properties();
// this will set host of server- you can change based on your
// requirement
props.put("mail.smtp.host", "smtp.gmail.com");
// set the port of socket factory
props.put("mail.smtp.socketFactory.port", "465");
// set socket factory
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// set the authentication to true
props.put("mail.smtp.auth", "true");
// set the port of SMTP server
props.put("mail.smtp.port", "465");
// This will handle the complete authentication
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("seleniumtest201#gmail.com", "Admin12!#");
}
});
try {
// Create object of MimeMessage class
Message message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress("seleniumtest201#gmail.com"));
// Set the recipient address
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("aniketgupta1993#gmail.com"));
// Add the subject link
message.setSubject("Test Case Execution Report");
// Create object to add multi media type content
BodyPart messageBodyPart1 = new MimeBodyPart();
// Set the body of email
messageBodyPart1.setText("This is auto-generated test case execution report");
// Create another object to add another content
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
// Mention the file which you want to send
String filename = "C://Users//aniket//sampleseleniumproject//test-output//emailable-report.html";
// Create data source and pass the filename
DataSource source = new FileDataSource(filename);
// set the handler
messageBodyPart2.setDataHandler(new DataHandler(source));
// set the file
messageBodyPart2.setFileName(filename);
// Create object of MimeMultipart class
Multipart multipart = new MimeMultipart();
// add body part 1
multipart.addBodyPart(messageBodyPart2);
// add body part 2
multipart.addBodyPart(messageBodyPart1);
// set the content
message.setContent(multipart);
// finally send the email
Transport.send(message);
System.out.println("=====Email Sent=====");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
You can use following code for the getting email when execution is completed and this put in teardown so you can get an Email notification in selenium webdriver, whenever scenario is failed/passed in between
public void tearDown()
{
private static void sendPDFReportByGMail(String from, String pass, String to, String subject, String body)
{
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
//Set from address
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//Set subject
message.setSubject(subject);
message.setText(body);
BodyPart objMessageBodyPart = new MimeBodyPart();
objMessageBodyPart.setText("Please Find The Attached Report File!");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(objMessageBodyPart);
objMessageBodyPart = new MimeBodyPart();
//Set path to the pdf report file
String filename = System.getProperty("user.dir")+"\\Default test.pdf";
//Create data source to attach the file in mail
DataSource source = new FileDataSource(filename);
objMessageBodyPart.setDataHandler(new DataHandler(source));
objMessageBodyPart.setFileName(filename);
multipart.addBodyPart(objMessageBodyPart);
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

Could not connect to SMTP host) error while sending mail

I am facing (Could not connect to SMTP host) error while sending mail by using javax.mail.jar. I am able to send mail through smtp.gmail.com, but when i am trying to connect to my company mail server i am getting the error. I tried from telnet and i am able to send mail from telnet and another python program is also running which is sending mail using the same mail server(ip and port), our bugzilla server is also running on same ip and port and it is successfully sends the mail. I tried to configure the same from java as well as from log4j through SMTP appender but no sucess.
Please guid me.
Thanks In Advance
my code as below -
private Session getSession()
{
Authenticator authenticator = new Authenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator
.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "25");
//properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", smtpServer);
properties.setProperty("mail.smtp.port", smtpPort);
return Session.getInstance(properties, authenticator);
}
private class Authenticator extends javax.mail.Authenticator
{
private final javax.mail.PasswordAuthentication authentication;
public Authenticator()
{
authentication =
new javax.mail.PasswordAuthentication(username, password);
}
#Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication()
{
return authentication;
}
}
public boolean sendEmail() throws MessagingException
{
boolean isSuccess = false;
String setBody = "";
String setSubject = "";
try
{
Message message = new MimeMessage(getSession());
setReceipients(message);
message.addFrom(new InternetAddress[]
{ new InternetAddress(emailFrom, "Notification") });
setSubject = emailSubject;
message.setSubject(setSubject);
setBody = emailBody + "\nThis is a System Generated Mail";
message.setContent(setBody, "text/plain");
Transport.send(message);
log.info("Mail Sent Successfully to - " + emailTo);
isSuccess = true;
}
catch (UnsupportedEncodingException ex)
{
log.error("Error in sending Mail without Attachment- "
+ ex.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
catch (SendFailedException e)
{
log.error("Invalid Addresses \"" + emailTo + "\" specified:"
+ e.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
catch (Exception e)
{
log.error("Error in sending Mail without Attachment- "
+ e.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
return isSuccess;
}
The JavaMail FAQ has debugging tips.
It would help to see the debug output from JavaMail.
Possibly you have a firewall or anti-virus program that is blocking port 25.

JavaMail not working properly

Hi When i tried the below code in my home pc it is working fine.
Properties props=new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", 465);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", true);
props.put("mail.smtp.port", 465);
Session sess=Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("user email ID","password");
}
});
try{
Message msg=new MimeMessage(sess);
msg.setFrom(new InternetAddress("sunnykeerthi#gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("sunnykeerthi#gmail.com"));
msg.setSubject("Hi this is mail");
msg.setText("Hi this is an email sent from java");
Transport.send(msg);
JOptionPane.showMessageDialog(null, "message has been sent");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
but when i tried the same in my office pc it is giving me the error as in the attached screen.
please help.
Is it possible that your company is filtering the port 25?
Can you send a mail from a local desktop client (outlook, thunderbird...) when you set gmail as smtp?
Can you try setting your company smtp server in your java code?

How can google app engine create new contacts?

I'm developing a membership sign up app for an organization on Google App Engine, for new members, they can use a sign up page to become a member, is there a way in Google App Engine to add new members as gmail contacts ? So each time a new user clicks a submit button with his info, a new gmail contact is auto generated and added to my contact list [ my gmail address is registered with the GAE app ].
Here is some of my code try to do that, but it doesn't add new contacts each a submit button is pressed :
String Add_New_Contact_Url="https://www.google.com/m8/feeds/contacts/default/full";
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8"); // UTF-8 GB18030
PrintWriter out=response.getWriter();
String Email=request.getParameter("Email");
if (Email==null || Email.trim().length()<1)
{
StrBuf=new StringBuffer("<Html><Head><Title>Signup</Title></Head>\n<Body>\n");
StrBuf.append("<P><Br><P><Br><P>\n");
StrBuf.append("<Table Border=1 Align=Center Cellpadding=8 Cellspacing=1><Tr Bgcolor=\"#0088FF\" Colspan=2><Th><Font Color=White>Sign up</Font></Th></Tr></Table>\n<P>\n");
StrBuf.append("<Center>\n");
StrBuf.append("<Form Name=Singles_Club_Signup_Form>\n");
StrBuf.append("<Table Border=1 Cellpadding=6 Cellspacing=1>\n");
...
StrBuf.append("<Tr><Td Align=Right><B><Font Size=3 Color=#0066FF>Email</Font></B></Td><Td><Input type=text name=Email size=36 /></Td></Tr>\n");
...
StrBuf.append("</Table>\n");
StrBuf.append("<P><Br><P>\n");
StrBuf.append("<Input type=submit value=Sign_Up/>\n");
StrBuf.append("</Form>\n");
StrBuf.append("</Center>\n");
StrBuf.append("</Body>\n</Html>");
}
else
{
try
{
LinkedHashMap<String,String> Key_Value_Pairs=new LinkedHashMap<String,String>();
String A_Contact=createContact(Email);
Key_Value_Pairs.put("A",A_Contact);
getFromUrlDoPost(Add_New_Contact_Url,Key_Value_Pairs); // Create new contact in Gmail account
}
catch (Exception e) { out.println(e.toString()); }
finally { if (pm!=null) pm.close(); }
}
}
String createContact(String Email)
{
return "<atom:entry xmlns:atom='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005'>\n"+
"<atom:category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/contact/2008#contact' />\n"+
"<gd:name>\n"+
"<gd:givenName>AAA</gd:givenName>\n"+
"<gd:familyName>BBB</gd:familyName>\n"+
"<gd:fullName>AAA BBB</gd:fullName>\n"+
"</gd:name>\n"+
"<atom:content type='text'>Notes</atom:content>\n"+
"<gd:email rel='http://schemas.google.com/g/2005#work' primary='true' address='"+Email+"' displayName='E. Bennet' />\n"+
"<gd:email rel='http://schemas.google.com/g/2005#home' address='liz#example.org' />\n"+
"<gd:phoneNumber rel='http://schemas.google.com/g/2005#work' primary='true'>\n"+
"(206)555-1212\n"+
"</gd:phoneNumber>\n"+
"<gd:phoneNumber rel='http://schemas.google.com/g/2005#home'>\n"+
"(206)555-1213\n"+
"</gd:phoneNumber>\n"+
"<gd:im address='liz#gmail.com' protocol='http://schemas.google.com/g/2005#GOOGLE_TALK' primary='true' rel='http://schemas.google.com/g/2005#home' />\n"+
"<gd:structuredPostalAddress rel='http://schemas.google.com/g/2005#work' primary='true'>\n"+
"<gd:city>Mountain View</gd:city>\n"+
"<gd:street>1600 Amphitheatre Pkwy</gd:street>\n"+
"<gd:region>CA</gd:region>\n"+
"<gd:postcode>94043</gd:postcode>\n"+
"<gd:country>United States</gd:country>\n"+
"<gd:formattedAddress>\n"+
"1600 Amphitheatre Pkwy Mountain View\n"+
"</gd:formattedAddress>\n"+
"</gd:structuredPostalAddress>\n"+
"</atom:entry>";
}
StringBuffer getFromUrlDoPost(String A_Url,LinkedHashMap Key_Value_Pairs) throws MalformedURLException,IOException
{
StringBuffer Text_Out=new StringBuffer(""),Text_In=new StringBuffer("");
String data="",key,value,inputLine;
try // Sending a POST Request Using a URL
{
// Construct data -- List the entries
for (Iterator it=Key_Value_Pairs.keySet().iterator();it.hasNext();)
{
key=it.next().toString();
value=Key_Value_Pairs.get(key).toString();
if (data.length()==0) data=URLEncoder.encode(key,"UTF-8")+"="+URLEncoder.encode(value,"UTF-8");
else data+="&"+URLEncoder.encode(key,"UTF-8")+"="+URLEncoder.encode(value,"UTF-8");
}
// Send data
URLConnection conn=new URL(A_Url).openConnection();
conn.setRequestProperty("Content-Type","application/atom+xml");
conn.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
Text_In.setLength(0);
// Get the response
BufferedReader rd=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((inputLine=rd.readLine()) != null) Text_In.append(inputLine+"\n");
wr.close();
rd.close();
}
catch (Exception e) { }
return Text_In;
}
It doesn't cause error either, what did I do wrong ? I suspect this line :
Key_Value_Pairs.put("A",A_Contact);
Because I don't know what to put in the place of "A" ?
Your users can authorize your application (via OAuth) to interact with their gmail contact list via the Contacts Data API.
I found out why : don't need to include google-collect-*.jar, source of error.

Resources