Javamail Auto-reply for my domain - jakarta-mail

Javamail Auto-reply
I would truly like to auto-reply to an email using Javamail.
I already use my domain email to send a confirmation code during registration.
What I need now is when an email is sent to choices#mydomain.com I can auto-reply with a canned email based on parsing out and reading the received email. It would be nice to include the username in the reply.
Thank you for your help!

This simplest approach is to write a program that monitors your mailbox and creates and sends a reply based on every message it sees. The JavaMail download bundle includes a sample program monitor.java that will get you started. The MimeMessage.reply method will be helpful. You'll have to fill in the content of the reply message yourself. Various other JavaMail sample programs will show you how to send a message once you've created it.
And don't forget to read the JavaMail FAQ.

Nice thinking John,I had the same problem in my project, in JSP and I solved it as shown below with java class as ReadingMail
package com;import java.io.*;import java.util.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
public class ReadingMail {
public static void main(String args[]) throws Exception {
try{
String host = "pop.gmail.com";
String user="username";
String password="password";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public String Manu()
{
String email=null;
try{
String host = "pop.gmail.com";
// String user = "xyz";
// String password = "12345";
String user="username#gmail.com";
String password="password";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
// System.out.println("SentDate : " + message[i].getSentDate());
//System.out.println("From : " + message[i].getFrom()[0]);
email=message[i].getFrom()[0]==null?null:((InternetAddress) message[i].getFrom()[0]).getAddress();
System.out.println("From addrss is..........................."+email);
// System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
catch(Exception e)
{
System.out.println(e);
}
return email;
}
You can fetch the username from the database and provide it as message in this program.

Related

How to make a connection localhost and my database

I'm using NetBeans to make a web application and using pgadmin4 for my database. The problem is when I'm making a connection pool.
This is my database http://prntscr.com/hzwn9h and I think the problem is because I want something like that http://prntscr.com/hzwnj2 but I have this http://prntscr.com/hzwnrw. I have tried a lot of solutions but it doesn't work and I don't know what else I have to do. One of the things I have tried was this https://rivaso.wordpress.com/2012/02/19/how-to-setup-a-new-database-in-postgresql-and-glassfish/ but unfortunately unsuccessful
Following code snippet shows how to establish connection for PostgreSQL using jdbc driver. Make sure to add jdbc driver to libraries.
public Connection DBConnect() {
try {
String host = "localhost";//host
String port = "5432";//db port
String db = "exp";//database name
String user = "root";//database username
String pass = "1234";//password
//connection url
String url = "jdbc:postgresql://" + host + ":" + port + "/" + db;
//initialize jdbc driver for postger sql
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);
//return connection
return conn;
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
return null;
}
}
reference : jdbc.postgresql.org
public static void main (String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/yourdatabasename";
Connection conn = DriverManager.getConnection(url, user,password);
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}

How to send FCM message from Appengine server on cloud code works local server

How to do it in cloud AppEngine without billing.
I am able to get Token from Javascript but sending messages to the server for notification. Create JSON object for downstream data/notification. On the server saying billing for the socket.
private void localappengine(HttpServletResponse response, String ENDPOINT_URL) throws IOException {
HttpClient client = new DefaultHttpClient();
Log.info("after client");
HttpPost post = new HttpPost(ENDPOINT_URL);
String deviceToken="cthG-hesotM:APA91bGg_tLg7TqvpY4aAvzHpyBK2mTTOT2KgO94tDFcLGPakcS9vmXkYEIe4Vh0Mo5ka1COfaXarUEJGWyqDdmVi_kujUfKDtE4C30eZwkPQATXnFrDPJxHxd8iouwsWuRcAk-ZYe_4";
PrintWriter out=response.getWriter();
response.getWriter().println("Hello from myservlet " );
// Create JSON object for downstream data/notification
JSONObject mainNotificationJsonObj = new JSONObject();
JSONObject outerBaseJsonObj = new JSONObject();
try {
// Notification payload has 'title' and 'body' key
mainNotificationJsonObj.put("title", "testing message");
mainNotificationJsonObj.put("body", "Hello I sent it");
// This will be used in case of both 'notification' or 'data' payload
outerBaseJsonObj.put("to", deviceToken);
// Set priority of notification. For instant chat setting
// high will
// wake device from idle state - HIGH BATTERY DRAIN
//outerBaseJsonObj.put(PRIORITY_KEY, PRIORITY_HIGH);
// Specify required payload key here either 'data' or
// 'notification'. We can even use both payloads in single
// message
outerBaseJsonObj.put("notification", mainNotificationJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
Log.info("before entity");
// Setup http entity with json data and 'Content-Type' header
StringEntity requestEntity = new StringEntity(outerBaseJsonObj.toString());
//(outerBaseJsonObj.toString(), APPLICATION_JSON);
String FIREBASE_SERVER_KEY= "key=AAAA6nN2BxI:APA91bHYotXML0siwL0Pm0LK5iXQ9Ik1kQtdB1ALbJrm5kseUk2zS5gJs6AMHVsX86exEE-JFsIF962YNY1yRyl3yFxGCyMBAH4OKwTn8Ff6vcd6vJMVXutNlP99X8AtOsW8_JIBkyEl";
// Setup required Authorization header
post.setHeader("Authorization", FIREBASE_SERVER_KEY);
post.setHeader("Content-Type", String.valueOf(APPLICATION_JSON));
Log.info("after header");
// Pass setup entity to post request here
post.setEntity(requestEntity);
// Execute apache http client post response
HttpResponse fcmResponse = client.execute(post);
Log.info("after client execute");
// Get status code from FCM server to debug error and success
System.out.println("RESPONSE_CODE" + fcmResponse.getStatusLine().getStatusCode());
// Get response entity from FCM server and read throw lines
BufferedReader rd = new BufferedReader(new InputStreamReader(fcmResponse.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
if (response != null) {
// Print out the response to webpage
PrintWriter out1;
out1 = response.getWriter();
out1.println(result);
System.out.println("This is Result - " + result);
}
}

LocationManager never gives Available status for GPS - Codenameone

I created a small app to test out the GPS features of codenameone, but found that it never give an Available status, only Temporarily Unavailable.
For my little test app, the relevant code is the following:
private void doRetrieveLocationAction() {
try {
Location location = LocationManager.getLocationManager().getCurrentLocation();
taLocationDisplay.setText(getGPSDetails() + "\n : " + location.toString());
} catch (Exception e) {
e.printStackTrace();
taLocationDisplay.setText("Error retrieving location:"
+ "\n"
+ getGPSDetails()
+ "\n " + e.getMessage());
ToastBar.showErrorMessage("Error retrieving location:"
+ "\n"
+ getGPSDetails()
+ "\n " + e.getMessage(), 5000);
}
}
private String getGPSDetails() {
StringBuilder sb = new StringBuilder();
sb.append("isEnabled: ").append(LocationManager.getLocationManager().isGPSEnabled());
sb.append("\nisGPSDetectionSupported: ").append(LocationManager.getLocationManager().isGPSDetectionSupported());
sb.append("\ngetStatus: ").append(LocationManager.getLocationManager().getStatus());
return sb.toString();
}
The status being Integer, is assigned the following values in the codenameone source code:
public static final int AVAILABLE = 0;
public static final int OUT_OF_SERVICE = 1;
public static final int TEMPORARILY_UNAVAILABLE = 2;
What I get when the GPS is off:
What I get Immediately after the GPS is turned on:
What I get after I waited a bit:
These results show that the Status never changes. When is the status supposed to change and how am I supposed to use that status? How do I know when the GPS can function or not?
This is being tested on Android
The GPS will be off by default unless you explicitly try to get "real" location by binding a listener to location events. So what you normally get is hybrid location and not GPS location.

How can I e-mail a .csv file in Codename One?

In my app, I create a file with a comma-separated array by writing to an OutputStream. Then I want to be able to share this by e-mail so a user can get the data. This is the code I use to create the file:
public String getLogFile(String logName) {
String path = FileSystemStorage.getInstance().getAppHomePath() + "exp " + logName + ".csv";
Set<Long> keys;
OutputStream os = null;
try {
os = FileSystemStorage.getInstance().openOutputStream(path);
Hashtable<Long, Integer> log = (Hashtable<Long, Integer>) dataStorage
.readObject(logName);
keys = log.keySet();
for (Long key : keys) {
String outString = (key + "," + log.get(key) + "\n");
System.out.println(outString);
byte[] buffer = outString.getBytes();
os.write(buffer);
}
} catch (IOException e) {
AnalyticsService.sendCrashReport(e, "Error writing log", false);
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return path;
}
Then, I've created a button that when pressed passes the path of the file to share. I've tried to use MIME types such as "text/plain" and "text/comma-separated-values", but that causes errors. Here is the code executed when the button is pressed.
public void exportLog(String logName) {
String path = dataBuffer.getLogFile(logName);
EmailShare email = new EmailShare();
// email.share("Here is your log.", path, "text/plain");
email.share("Here is your log.", path, "text/comma-separated-values");
}
When pressed (in the simulator). I get this stack after selecting the dummy e-mail contact to send to:
java.lang.NullPointerException
at com.codename1.impl.javase.JavaSEPort.scale(JavaSEPort.java:3483)
at com.codename1.ui.Image.scale(Image.java:963)
at com.codename1.ui.Image.scaledImpl(Image.java:933)
at com.codename1.ui.Image.scaled(Image.java:898)
at com.codename1.impl.javase.JavaSEPort$60.save(JavaSEPort.java:6693)
at com.codename1.share.ShareForm.<init>(ShareForm.java:75)
at com.codename1.share.EmailShare$1$2$1.actionPerformed(EmailShare.java:102)
at com.codename1.ui.util.EventDispatcher.fireActionSync(EventDispatcher.java:455)
at com.codename1.ui.util.EventDispatcher.fireActionEvent(EventDispatcher.java:358)
at com.codename1.ui.List.fireActionEvent(List.java:1532)
at com.codename1.ui.List.pointerReleasedImpl(List.java:2011)
at com.codename1.ui.List.pointerReleased(List.java:2021)
at com.codename1.ui.Form.pointerReleased(Form.java:2560)
at com.codename1.ui.Component.pointerReleased(Component.java:3108)
at com.codename1.ui.Display.handleEvent(Display.java:2017)
at com.codename1.ui.Display.edtLoopImpl(Display.java:1065)
at com.codename1.ui.Display.mainEDTLoop(Display.java:994)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
The EmailShare class expects a path to an image file not an arbitrary file as its second argument so loading that fails.
The Message class is better suited for that indeed. You can also use the cloud send option which won't launch the native email app. E.g. the Log class includes that ability directly thru the Log.sendLog API.
It looks like the Messages class is better suited for this task, and should allow attachments, etc.

Error in JavaMail when running Selenium

I'm trying to extract an email running selenium and maven but I get the following error when trying to connect:
javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.UnknownHostException: pop.google.com
at com.sun.mail.pop3.POP3Store.protocolConnect
But when I run the same exact code in a different project without selenium it works, any idea what's causing this?
public class EmailService {
private static String SERVER;
private static String USER;
private static String PASSWORD;
private static final String TEXT_FROM="SMS from";
/**
* Constructor to setup imap info
* #param server email server to connect
* #param usr email address of user
* #param passwd password of user
*/
public EmailService(String server, String usr, String passwd){
SERVER = server;
USER = usr;
PASSWORD = passwd;
}
public static String receive(String type, String receiver, Date d) {
Store store = null;
Folder folder= null;
SubjectTerm subject;
RecipientStringTerm recipient = new RecipientStringTerm(Message.RecipientType.TO,USER);
try{
//Get session
Properties props = new Properties();
//props.setProperty("mail.store.protocol","imaps");
props.put("mail.pop3.host", SERVER);
props.put("mail.pop3.port", "995");
props.put("mail.pop3.starttls.enable", "true");
//Session session = Session.getInstance(props, null);
Session session = Session.getDefaultInstance(props);
//Get message store and connect
store = session.getStore("pop3s");
store.connect(SERVER,USER,PASSWORD);
//Get default folder
folder = store.getDefaultFolder();
if(folder == null) throw new Exception("No Default folder");
//Get Inbox
folder = folder.getFolder("INBOX");
if(folder == null) throw new Exception ("No Inbox");
//Open folder for read only
folder.open(Folder.READ_ONLY);
That's because there is no host named "pop.google.com". Maybe you meant "pop.gmail.com"?
It probably works on some machines because of the first common mistake described in this JavaMail FAQ entry.

Resources