how to send body message in RTF format using JavaMail API? - jakarta-mail

I am working on an application to send e-mail(s). I want to sent body message as RTF format. When i try to send message in RTF format it creates an attachment file rather than body message.
public boolean run() {
System.out.println("START SENDING");
Transport transport = null;
Session mailSession = null;
Properties props = null;
try {
props = new Properties();
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.port", port);
props.put("mail.smtp.user", user);
props.put("mail.smtp.password", password);
props.put("mail.smtp.auth", auth);
props.put("mail.smtp.ssl.enable", false);
props.put("mail.smtp.ssl.trust", "*");
mailSession = Session.getInstance(props, new SMTPAuthenticator(user, password));
transport = mailSession.getTransport("smtp");
MimeMessage message = prepareMessage(mailSession, "UTF-8",
user, subject, HtmlMessage, recipientsString);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(HtmlMessage);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
if (file != null) {
DataSource source = new FileDataSource(file.getAbsoluteFile());
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
} else {
/*HtmlMessage (String)*/
message.setContent(HtmlMessage, "text/rtf");
}
transport.connect();
Transport.send(message);
System.out.println("SEND DONE");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Unable to send Message.");
ex.printStackTrace();
} finally {
System.out.println(mailSession.getProperty("mail.smtp.user"));
mailSession = null;
props.clear();
smtpServer = null;
user = null;
password = null;
if (t != null && t.isAlive()) {
t.interrupt();
t = null;
}
this.dispose();
}
return false;
}

To have a message body part be inline instead of an attachment, do this:
messageBodyPart.setDisposition(Part.INLINE);

Related

sending mail using javamail getting authentication issue

When I tried to send mail using following code, I got authentication issues.
Here's my code:
public class NewSendMail {
String to = "********";
String subject = "subject";
String msg ="email text....";
final String from ="*******";
final String password ="******";
public NewSendMail(){
}
public boolean sendMymail(){
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
// Session session = Session.getDefaultInstance(props);
//session.setDebug(true);
Transport transport;
InternetAddress addressFrom = null;
try {
transport = session.getTransport();
addressFrom = new InternetAddress(from);
MimeMessage message = new MimeMessage(session);
message.setSender(addressFrom);
message.setSubject(subject);
message.setContent(msg, "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
transport.connect();
Transport.send(message);
transport.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
It is throwing a javax.mail.AuthenticationFailedException.
How can I fix the issue?
The following code may help you
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(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.ssl.trust", 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 {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
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();
}
}
}
This code worked for me, If it is not working for you, Check your jar files
I tell everyone who asks for JavaMail help the same things. (I wonder why they call it a FAQ?)
Fix these common mistakes.
Follow this example for Gmail.
Turn on session debugging to get more details of what's going wrong, and post the output if you still can't figure it out.
Either you're sending the wrong username or password, or the server is rejecting your login attempt for other reasons, perhaps because you haven't enabled less secure apps.

android app development-passing parameter to database

I am trying to connect my app to database on localhost server.I can connect to it ut the problem is how to pass the parameter from app to php script.for eg i want all names having age less than 10 so i will pass the parameter to php.below is my code for connecting to database.please provide good reference
/* */
enter code here
public class TestExternalDatabaseActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.enableDefaults(); //STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/tahseen0amin/php/getAllCustomers.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Couldnt connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+
"Age : "+json.getInt("Age")+"\n"+
"Mobile Using : "+json.getString("Mobile")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
}

How to write the body part while sending an email?

While sending the email after the script completed i am not able to add any body part. I want to add body like,
Hi xyz,
Please find the attached the reports attached.
With Best Regards,
Abc.
I am using the below code for sending the email . Can anyone please guide me how to send email.
package util;
//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendMail
{
public static void zipAndSendReport()
{
TestUtil.zip(System.getProperty("user.dir") +"\\HtmlReports");
String[] to={"xyz#xyz.com"};
String[] cc={"xyzff#xyz.com","xyzaa#xyz.com"};
String[] bcc={"xyzrwer#xyz.com"};
//This is for google
SendMail.sendMail("acv.ddg#gmail.com",
"070122dasdad3183",
"smtp.gmail.com",
"465",
"true",
"true",
true,
"javax.net.ssl.SSLSocketFactory",
"false",
to,
cc,
bcc,
"Automation test Reports",
"Please find the reports attached.\n\n Regards\nWebMaster",
System.getProperty("user.dir")+"\\Reports.zip",
"Reports.zip");
}
public 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,
String attachmentPath,
String attachmentName){
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);
// props.put("mail.smtps.auth", "true");
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 session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication("acv.ddg#gmail.com","070122sd3183"); }
});
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
//attachment start
// create the message part
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(attachmentPath);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(attachmentName);
multipart.addBodyPart(messageBodyPart);
// attachment ends
// Put parts in message
msg.setContent(multipart);
msg.setFrom(new InternetAddress(userName));
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)
{
mex.printStackTrace();
return false;
}
}
}
Please let us know will this code work or is there any better way of doing this?
Thanks,
Sudhansu
Your MimeMessage can either have text set via setText() or a multipart-body.
Since your use atteachments you have to use multipart. To add some plain text to the message create another MimeBodyPart and add it as the first to your Multipart:
....
Multipart multipart = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(text);
mmp.addBodyPart(textPart);
MimeBodyPart messageBodyPart = new MimeBodyPart();
....

get user by access google oauth2 token

I need login user in server side by access token and get their user infomrmations. it is possible ?
Im looks in com.google.appengine.api but Im not find it.
I get acces token in client side using google oauth2 and after send to server.
thanks.
I found the solution with calling url to google api.
public UserInfo login(String token) {
String json = getJsonDataFromUrl("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token);
UserInfo userInfo = new UserInfo();
Gson gson = new Gson();
try{
userInfo = gson.fromJson(json, UserInfo.class);
userInfo.logined = true;
HttpSession session = getRequest().getSession();
session.setAttribute("userKey", userInfo.encodedKey);
}catch (Exception ex){
log.log(Level.WARNING, ex.getMessage());
throw ex;
}
return userInfo;
}
private String getJsonDataFromUrl(String aurl){
String json = "";
try {
URL url = new URL(aurl);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
json+=line;
}
reader.close();
} catch (MalformedURLException e) {
log.log(Level.SEVERE, e.getMessage());
return null;
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
return null;
}
return json;
}

Google OAuth2.0 - Windows phone 7

Experts,
I'm new to OAuth,
I'm writing an small App in windows Phone 7, I'm using OAuth2 for google contacts, I need to get the initial URL API (1) to get the Token
1) https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.google.com/m8/feeds/&redirect_uri=REDIRECT_URI&client_id=CLIENT_ID&hl=en-US&from_login=1&as=NEW_AS&pli=1
I got the success code, and when I'm trying to use this
https://www.google.com/m8/feeds/contacts/default/full?access_token=TOKEN_CODE
but I'm getting 401 error back,
Can you please advice, what mistake i'm going.
I've taken Twitter OAuth example as base, and doing modifications.
CODE
var uri = new Uri(url);
var request = BuildOAuthWebRequest(url, null);
MakeGetRequest(callback, request);
private static HttpWebRequest BuildOAuthWebRequest( string url, string realm)
{
var header = new StringBuilder();
var request = (HttpWebRequest)WebRequest.Create(url);
return request;
}
private static void MakeGetRequest(EventHandler<OAuthEventArgs> callback, HttpWebRequest request)
{
var asyncState = request.BeginGetResponse(new AsyncCallback((asyncRes) =>
{
HttpWebResponse response = null;
try
{
//request has returned
response = (HttpWebResponse)request.EndGetResponse(asyncRes);
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
var token = sr.ReadToEnd();
callback(null, new OAuthEventArgs() { Response = token });
}
}
}
catch (WebException we)
{
string t = new StreamReader(we.Response.GetResponseStream()).ReadToEnd();
callback(null, new OAuthEventArgs() { Error = we, ErrorMessage = t, IsError = true });
}
catch (Exception e)
{
callback(null, new OAuthEventArgs() { Error = e, ErrorMessage = e.Message, IsError = true });
}
finally
{
if (response != null)
response.Close();
}
}), null);
}

Resources