how to send HTML email - html

I have to send HTML file via email but not as attachment.
Message simpleMessage = new MimeMessage(mailSession);
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It is sending email simply with text message.
I want to send HTML content which is stored in another file but not as attachment

Don't upcast your MimeMessage to Message:
MimeMessage simpleMessage = new MimeMessage(mailSession);
Then, when you want to set the message body, either call
simpleMessage.setText(text, "utf-8", "html");
or call
simpleMessage.setContent(text, "text/html; charset=utf-8");
If you'd rather use a charset other than utf-8, substitute it in the appropriate place.
JavaMail has an extra, useless layer of abstraction that often leaves you holding classes like Multipart, Message, and Address, which all have much less functionality than the real subclasses (MimeMultipart, MimeMessage, and InternetAddress) that are actually getting constructed...

Here is my sendEmail java program. It's good to use setContent method of Message class object.
message.setSubject(message_sub);
message.setContent(message_text, "text/html; charset=utf-8");
sendEmail.java
package employee;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
public class SendEmail {
public static void sendEmail(String message_text, String send_to,String message_sub ) throws UnsupportedEncodingException {
final String username = "hello#xyz.com";
final String password = "password";
Properties prop = new Properties();
prop.put("mail.smtp.host", "us2.smtp.mailhostbox.com"); //replace your host address.
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true"); //TLS
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender#xyz.com", "Name from which mail has to be sent"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(send_to)
);
message.setSubject(message_sub);
message.setContent(message_text, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

Related

Can we use the same signer object to sign all the requests?

I need to make mutiple rest api calls for fetching instance, volume and vnic details. Can i reuse the same signer object created for signing the other calls?
Signer object method
public RequestSigner getSigner(Properties properties, String pemFilePath, String apiKey) {
InputStream privateKeyStream;
PrivateKey privateKey = null;
try {
privateKeyStream = Files.newInputStream(Paths.get(pemFilePath));
privateKey = PEM.readPrivateKey(privateKeyStream);
} catch (InvalidKeySpecException e) {
// throw new RuntimeException("Invalid format for private key");
properties.setProperty(OracleCloudConstants.CUSTOM_DC_ERROR,
FormatUtil.getString("am.webclient.oraclecloud.customdc.invalidformat"));
AMLog.debug("OracleCloudDataCollector::CheckAuthentication()::Invalid format for private key::"
+ e.getMessage());
e.printStackTrace();
} catch (IOException e) {
properties.setProperty(OracleCloudConstants.CUSTOM_DC_ERROR,
FormatUtil.getString("am.webclient.oraclecloud.customdc.failedload"));
AMLog.debug(
"OracleCloudDataCollector::CheckAuthentication()::Failed to load private key::" + e.getMessage()); //No I18N
e.printStackTrace();
// throw new RuntimeException("Failed to load private key");
}
RequestSigner signer = null;
if (privateKey != null) {
signer = new RequestSigner(apiKey, privateKey);
}
return signer;
}
One signer object may be used to sign multiple requests. In fact, the SDK implementation does this too.
It is not clear what version of the SDK you are using. In version 1.5.7 (the most recent at the time of writing), com.oracle.bmc.http.signing.RequestSigner (https://github.com/oracle/oci-java-sdk/blob/master/bmc-common/src/main/java/com/oracle/bmc/http/signing/RequestSigner.java#L16) is an interface which cannot be new’ed as per the snippet above.

How do I send a HTTP request using OAUTH2 in Android?

I am trying to retrieve the data from my account by connecting to the Fitbit API. I have my app returning the Access Token I need to make the HTTP Request that returns the JSON but anything that I try, it returns an error. I have two Activities - MainActivity.java and TestActivity.java
In MainActivity.java I am simply opening a Chrome Custom Tab to direct the user to the Fitbit Authentication(Login) page. Once the user enters their details they are redirected back to the TestActivity.java as per the Fitbit API documentation. I am then printing the Acess Token which proves to me that it is connecting to the API.
What I need to do it make an HTTP request to returns the sleep data in JSON format. I know how to do it in Java but I am unsure how to do it in Android using the AsyncTask way. Any help is appreciated!
public class TestActivity extends AppCompatActivity {
String string;
String token;
#Override
protected void onNewIntent(Intent intent) {
string = intent.getDataString();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
onNewIntent(getIntent());
//Toast.makeText(TestActivity.this, string , Toast.LENGTH_LONG).show();
Log.e("TAG", string);
Log.e("TAG", string.substring(string.indexOf("&access_token")+14));
token = string.substring(string.indexOf("&access_token")+14);
Context context = getApplicationContext();
Toast toast = Toast.makeText(context,"Access Token: "+ token,Toast.LENGTH_LONG );
Log.i("TAG", "Access Token: "+ token);
new JSONTask().execute("https://api.fitbit.com/1.2/user/-/sleep/date/2018-01-30.json");
}
public class JSONTask extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try
{
URL url = new URL(params[0]);
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer " + token);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) !=null)
{
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
Log.i("TAG", s);
}
}
I ended up having a breakthrough with this question. I figured out that I was extracting the Access Token incorrectly. So, instead of doing the following:
token = string.substring(string.indexOf("&access_token")+14);
I instead had to use this:
token = string.substring(string.indexOf("&access_token")+36,308);
The App was then able to make the necessary HTTP request to the Fitbit API which returned the JSON data that I needed.
One order of codes should be changed for preventing FC.
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer " + token);

Mockito Stubbing

Listed below is a method I am trying to test using Junit and Mockito
Java Code
public String getAuthenticationService() {
Authentication endpoint;
String token = "";
try {
URL wsdlURL = new URL(authenticationURL);
SoapService service = new SoapService(wsdlURL,
new QName("SomeQName",
"SoapService"));
endpoint = service.getAuthenticationPort();
token = endpoint.authenticate(username, password);
} catch (Exception e) {
throw new GenericException(
"OpenText AuthenticationService not working Error is "
+ e.toString());
}
return token;
}
Junit method
public void testGetAuthenticationService()
throws AuthenticationException_Exception {
AuthenticationService mockService = Mockito
.mock(AuthenticationService.class);
Authentication mockEndpoint = Mockito.mock(Authentication.class);
Mockito.when(mockService.getAuthenticationPort()).thenReturn(
mockEndpoint);
Mockito.when(mockEndpoint.authenticate(username, password)).thenReturn(
token);
}
When I run the Junit test case the endpoint.authenticate tries to connect to the actaul soap service, and the method stubbing is not working, what am I doing wrong here
Your mockService seems to be a good replacement for your SoapService, but you aren't giving yourself an opportunity to refer to it in your code. Your test calls the code, which calls the SoapService constructor, so you get a real service. Consider this refactor:
public String getAuthenticationService() {
try {
URL wsdlURL = new URL(authenticationURL);
SoapService service = new SoapService(wsdlURL,
new QName("SomeQName", "SoapService"));
return getAuthenticationService(service);
} catch (Exception e) {
throw new GenericException(
"OpenText AuthenticationService not working Error is "
+ e.toString());
}
}
/** package-private for testing - call this from your test instead */
String getAuthenticationService(AuthenticationService service) {
try {
Authentication endpoint = service.getAuthenticationPort();
String token = endpoint.authenticate(username, password);
return token;
} catch (Exception e) {
throw new GenericException(
"OpenText AuthenticationService not working Error is "
+ e.toString());
}
}
Now you can pass your mockService into getAuthenticationService(service) and your code will use your mock rather than the SoapService it creates inline.
As as alternative, you can also give yourself a seam by wrapping the SoapService constructor:
/** overridden in tests */
protected AuthenticationService createSoapService(String url, QName qname) {
return new SoapService(url, qname);
}
public String getAuthenticationService() {
try {
URL wsdlURL = new URL(authenticationURL);
SoapService service = createSoapService(wsdlURL,
new QName("SomeQName", "SoapService"));
Authentication endpoint = service.getAuthenticationPort();
String token = endpoint.authenticate(username, password);
return token;
} catch (Exception e) {
throw new GenericException(
"OpenText AuthenticationService not working Error is "
+ e.toString());
}
}
// in your test:
SystemUnderTest yourSystem = new YourSystem() {
#Override protected AuthenticationService createAuthenticationService(
String url, QName qname) {
return mockService;
}
}

How to solve could not convert socket to TLS

this is my code mention in that box.so please check this code and give me right answer.this code is totally run in my system and run successfully and show build successful but message does not send in mail ids.so please help me.
Thanks in advance
this is my code.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Main1
{
String d_email = "xyz#ibm.com",
d_password = "*******",
d_host = "blr-outlook.ibm.com",
d_port = "25",
m_to = "xyz#ibm.com",
m_subject = "Testing",
m_text = "Hey, this is the testing email using blr-outlook.ibm.com";
public static void main(String[] args)
{
String[] to={"xyz#ibm.com"};
String[] cc={"xyz#ibm.com"};
String[] bcc={"xyz#ibm.com"};
//This is for google
Main1.sendMail("xyz#ibm.com", "password", "blr-outlook.ibm.com",
"25", "true", "true",
true, "javax.net.ssl.SSLSocketFactory", "false",
to, cc, bcc,
"hi baba don't send virus mails..",
"This is my style...of reply..If u send virus mails..");
}
public synchronized static boolean sendMail(
String userName, String passWord, String host,
String port, String starttls, String auth,
boolean debug, String socketFactoryClass, String fallback,
String[] to, String[] cc, String[] bcc,
String subject, String text)
{
Properties props = new Properties();
//Properties props=System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if(!"".equals(port)) {
props.put("mail.smtp.port", port);
}
if(!"".equals(starttls)) {
props.put("mail.smtp.starttls.enable",starttls);
}
props.put("mail.smtp.auth", auth);
if(debug) {
props.put("mail.smtp.debug", "true");
} else {
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port)) {
props.put("mail.smtp.socketFactory.port", port);
}
if(!"".equals(socketFactoryClass)) {
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
}
if(!"".equals(fallback)) {
props.put("mail.smtp.socketFactory.fallback", fallback);
}
try
{
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress("blr-outlook.ibm.com"));
for(int i=0;i<to.length;i++) {
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to[i]));
}
for(int i=0;i<cc.length;i++) {
msg.addRecipient(Message.RecipientType.CC,
new InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++) {
msg.addRecipient(Message.RecipientType.BCC,
new InternetAddress(bcc[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
}
catch (Exception mex)
{
return false;
}
}
}
There are so many examples available in the net...even tutorialspoint have well explained examples....check it out here.....
http://www.tutorialspoint.com/javamail_api/javamail_api_overview.htm
i have used java mail api for mailing purposes and it works good enough.....i am away from home so i can't share the code with you now....
Edit:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailTLS {
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
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("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
try this....authentication is not mandatory....and if you are using any kinda app you need to change your gmail account setting to allow access for less secured apps....

Using XPages to get data from managed bean

I am trying to create a list of Twitter users, populating it with the number of followers for the user and their profile image. Because of Twitter's API, you need to get an access token for your application prior to using their REST API. I thought the best way to do this was via Java and a managed bean. I posted the code below, which currently works. I get the access token from Twitter, then make the API call to get the user info, which is in JSON.
My question is, what is the best way to parse the JSON and iterate over a list of user names to create a table/grid on the XPage?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class TwitterUser implements Serializable {
private static final String consumerKey = "xxxx";
private static final String consumerSecret = "xxxx";
private static final String twitterApiUrl = "https://api.twitter.com";
private static final long serialVersionUID = -2084825539627902622L;
private static String accessToken;
private String twitUser;
public TwitterUser() {
this.twitUser = null;
}
public String getTwitterUser(String screenName) {
try {
this.requestTwitterUserInfo(screenName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return twitUser;
}
public void setTwitterUser() {
twitUser = twitUser;
}
//Encodes the consumer key and secret to create the basic authorization key
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
return new String();
}
}
//Constructs the request for requesting a bearer token and returns that token as a string
private static void requestAccessToken() throws IOException {
HttpsURLConnection connection = null;
String endPointUrl = twitterApiUrl + "/oauth2/token";
String encodedCredentials = encodeKeys(consumerKey,consumerSecret);
String key = "";
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Your Program Name");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
writeRequest(connection, "grant_type=client_credentials");
// Parse the JSON response into a JSON mapped object to fetch fields from.
JSONObject obj = (JSONObject)JSONValue.parse(readResponse(connection));
if (obj != null) {
String tokenType = (String)obj.get("token_type");
String token = (String)obj.get("access_token");
accessToken = ((tokenType.equals("bearer")) && (token != null)) ? token : "";
}
else {
accessToken = null;
}
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
private void requestTwitterUserInfo(String sn) throws IOException {
HttpsURLConnection connection = null;
if (accessToken == null) {
requestAccessToken();
}
String count = "";
try {
URL url = new URL(twitterApiUrl + "/1.1/users/show.json?screen_name=" + sn);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Your Program Name");
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setUseCaches(false);
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
twitUser = readResponse(connection);
}
//Writes a request to a connection
private static boolean writeRequest(HttpsURLConnection connection, String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
}
catch (IOException e) { return false; }
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpsURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
}
catch (IOException e) { return new String(); }
}
}
A few pointers:
Domino has the Apache HTTP client classes. They tend to be more robust than raw HTTP connections
Define a new class as a bean that contains all values that you want to see per row. You only need the getters public
add a method to your managed bean Collection getAllData()
bind that to a repeat control
you then can use repeatvar.someProperty in column values in EL
use better names than I just used