-
-
Save mistrydarshan99/fef4bd27240dd94de207 to your computer and use it in GitHub Desktop.
Test Alert and mail sender
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import android.annotation.TargetApi; | |
import android.app.Activity; | |
import android.app.PendingIntent; | |
import android.content.BroadcastReceiver; | |
import android.content.ContentValues; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.IntentFilter; | |
import android.net.ConnectivityManager; | |
import android.net.Uri; | |
import android.os.AsyncTask; | |
import android.os.Build; | |
import android.os.Handler; | |
import android.os.Looper; | |
import android.os.PowerManager; | |
import android.os.StrictMode; | |
import android.telephony.SmsManager; | |
import android.widget.Toast; | |
public class TestAlert { | |
static Context context; | |
private static PowerManager.WakeLock mWakeLock; | |
private static ConnectivityManager mConnMgr; | |
private static int usedFeature; | |
/* | |
* Stolen directly from android source | |
* https://android.googlesource.com/platform | |
* /frameworks/opt/telephony/+/d1ae7c941a4ea5f45aeca4171d75c1283a78039d | |
* /src/java/com/android/internal/telephony/Phone.java | |
*/ | |
private static String FEATURE_ENABLE_MMS = "enableMMS"; | |
/* | |
* https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master | |
* /telephony/java/com/android/internal/telephony/PhoneConstants.java | |
*/ | |
private static final int APN_ALREADY_ACTIVE = 0; | |
private static final int APN_REQUEST_STARTED = 1; | |
public static void sendSMS(final Context c, String message) { | |
final boolean sendSMS = Settings.getPrefs(c).getBoolean("mg_send_sms", false); | |
if(!sendSMS) { | |
return; | |
} | |
context = c; | |
SmsManager smsManager = SmsManager.getDefault(); | |
final String target = Settings.getPrefs(c).getString("mg_target_sms", | |
""); | |
final String smsBody = "Alert from " + Settings.getDeviceID(c) + ":\n" | |
+ message; | |
if (target.trim().length() == 0) { | |
Logs.forceToast(c, "Error! No SMS Receiptient set.", | |
Toast.LENGTH_SHORT); | |
return; | |
} | |
try { | |
String SENT = "SMS_SENT"; | |
String DELIVERED = "SMS_DELIVERED"; | |
PendingIntent sentPI = PendingIntent.getBroadcast(c, 0, new Intent( | |
SENT), 0); | |
PendingIntent deliveredPI = PendingIntent.getBroadcast(c, 0, | |
new Intent(DELIVERED), 0); | |
// ---when the SMS has been sent--- | |
c.registerReceiver(new BroadcastReceiver() { | |
public void onReceive(Context arg0, Intent arg1) { | |
switch (getResultCode()) { | |
case Activity.RESULT_OK: | |
saveSMS(c, target, smsBody); | |
Logs.forceToast(c, "SMS sent", Toast.LENGTH_SHORT); | |
break; | |
case SmsManager.RESULT_ERROR_GENERIC_FAILURE: | |
Logs.forceToast(c, "Error: Generic failure", | |
Toast.LENGTH_SHORT); | |
break; | |
case SmsManager.RESULT_ERROR_NO_SERVICE: | |
Logs.forceToast(c, "Error: No service", | |
Toast.LENGTH_SHORT); | |
break; | |
case SmsManager.RESULT_ERROR_NULL_PDU: | |
Logs.forceToast(c, "Error: Null PDU", | |
Toast.LENGTH_SHORT); | |
break; | |
case SmsManager.RESULT_ERROR_RADIO_OFF: | |
Logs.forceToast(c, "Error: Radio off", | |
Toast.LENGTH_SHORT); | |
break; | |
} | |
} | |
}, new IntentFilter(SENT)); | |
// ---when the SMS has been delivered--- | |
c.registerReceiver(new BroadcastReceiver() { | |
@Override | |
public void onReceive(Context arg0, Intent arg1) { | |
switch (getResultCode()) { | |
case Activity.RESULT_OK: | |
Logs.forceToast(c, "SMS delivered", Toast.LENGTH_SHORT); | |
break; | |
case Activity.RESULT_CANCELED: | |
Logs.forceToast(c, "SMS not delivered", | |
Toast.LENGTH_SHORT); | |
break; | |
} | |
} | |
}, new IntentFilter(DELIVERED)); | |
// debug info too prepend on sms | |
String smsPrepend = ""; | |
// If it is sandbox mode, show toast, prepend the info to SMS | |
if (Settings.getPrefs(c).getBoolean("mg_sandbox", true)) { | |
Logs.forceToast(c, | |
"[Sandbox mode] SMS saved to inbox of messaging app.", | |
Toast.LENGTH_LONG); | |
smsPrepend = "[Unsent] \n"; | |
saveSMS(c, target, smsPrepend + smsBody); | |
} else { | |
// send sms | |
smsManager.sendTextMessage(target, null, smsBody, sentPI, | |
deliveredPI); | |
Logs.forceToast(c, "Sending SMS...", Toast.LENGTH_SHORT); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
private static void saveSMS(Context c, String target, String message) { | |
// save the message to inbox | |
ContentValues values = new ContentValues(); | |
values.put("address", target); | |
values.put("body", message); | |
c.getContentResolver().insert(Uri.parse("content://sms/sent"), values); | |
} | |
public static void sendEmail(final Context c, final String body) { | |
final boolean sendEmail = Settings.getPrefs(c).getBoolean("mg_send_email", false); | |
if(!sendEmail) { | |
return; | |
} | |
String senderID = Settings.getDeviceID(c); | |
String smtpHost = Settings.getPrefs(c).getString("mg_smtp_server", ""); | |
String smtpPort = Settings.getPrefs(c).getString("mg_smtp_port", ""); | |
String smtpUser = Settings.getPrefs(c).getString("mg_smtp_user", ""); | |
String smtpPass = Settings.getPrefs(c).getString("mg_smtp_pass", ""); | |
final String emailTarget = Settings.getPrefs(c).getString( | |
"mg_target_email", ""); | |
String emailTargets[] = { emailTarget }; | |
try { | |
final MailSender sender = new MailSender(smtpUser, smtpPass, | |
smtpHost, smtpPort); | |
sender.setTo(emailTargets); | |
sender.setFrom(smtpUser); | |
sender.setSubject("Alerts from " + senderID); | |
sender.setBody(body); | |
Logs.show("Sending " + smtpHost + " " + smtpPort + " " + smtpUser | |
+ " " + smtpPass + " " + emailTarget + " " + body); | |
strictModeHack(); | |
/* | |
* We must execute AsyncTask from UI thread! | |
*/ | |
Handler handler = new Handler(Looper.getMainLooper()); | |
handler.post(new Runnable() { | |
@Override | |
public void run() { | |
AsyncTask<String, String, String> sendEmailTask = new AsyncTask<String, String, String>() { | |
@Override | |
public String doInBackground(String... arg) { | |
try { | |
if (sender.send()) { | |
return "yes"; | |
} else { | |
return "no"; | |
} | |
} catch (Exception e) { | |
// Logs.show(e.getMessage()); | |
e.printStackTrace(); | |
return "err"; | |
} | |
} | |
protected void onPreExecute() { | |
Logs.forceToast(c, "Sending email...", | |
Toast.LENGTH_LONG); | |
/* | |
* Read from preferences whether the Email is set to | |
* be sent using Wifi or 3G connection only. Enable | |
* 3G mode if required | |
*/ | |
String sendEmailUsing = Settings.getPrefs(c) | |
.getString( | |
Values.Global.KEY_EMAIL_CONNECTION, | |
"0"); | |
switch (Integer.valueOf(sendEmailUsing)) { | |
// 0 is Any | |
case 0: | |
break; | |
// 1 is Wifi Only | |
case 1: | |
break; | |
// 2 is 3G Only | |
case 2: | |
try { | |
beginSimultaneous3G(c); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
}; | |
@Override | |
protected void onPostExecute(String result) { | |
String msg = "Mail status unknown."; | |
if (result.equalsIgnoreCase("yes")) { | |
msg = "Mail sent successfully!"; | |
} else if (result.equalsIgnoreCase("no")) { | |
msg = "Mail could not be sent by network error!"; | |
} else if (result.equalsIgnoreCase("err")) { | |
msg = "Mail could not be sent due to network error."; | |
} | |
Logs.forceToast(c, msg, Toast.LENGTH_LONG); | |
Logs.print(msg, c); | |
}; | |
}; | |
if (Settings.getPrefs(c).getBoolean("mg_sandbox", true)) { | |
Logs.forceToast(c, "[Sandbox Mode]\nTo: " + emailTarget | |
+ "\n" + body, Toast.LENGTH_LONG); | |
} else { | |
sendEmailTask.execute(""); | |
} | |
} | |
}); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
@TargetApi(Build.VERSION_CODES.GINGERBREAD) | |
private static void strictModeHack() { | |
if (android.os.Build.VERSION.SDK_INT > 9) { | |
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() | |
.permitAll().build(); | |
StrictMode.setThreadPolicy(policy); | |
} | |
} | |
/** | |
* Enable 3G connection simultaneously along with Wifi | |
*/ | |
protected static int beginSimultaneous3G(Context context) throws IOException { | |
Logs.print("Opening 3G connection.", context); | |
// createWakeLock(); | |
// Use connectionmanager to switch to 3G data | |
if (mConnMgr == null) { | |
mConnMgr = (ConnectivityManager) context | |
.getSystemService(Context.CONNECTIVITY_SERVICE); | |
} | |
int result = -1; | |
int[] apnTypes = new int[] { ConnectivityManager.TYPE_MOBILE, | |
ConnectivityManager.TYPE_MOBILE_MMS, | |
ConnectivityManager.TYPE_MOBILE_DUN, | |
ConnectivityManager.TYPE_MOBILE_HIPRI, | |
ConnectivityManager.TYPE_MOBILE_SUPL }; | |
for (int i = 0; i < apnTypes.length; i++) { | |
result = mConnMgr.startUsingNetworkFeature(apnTypes[i], | |
FEATURE_ENABLE_MMS); | |
switch (result) { | |
case APN_ALREADY_ACTIVE: | |
case APN_REQUEST_STARTED: | |
// acquireWakeLock(); | |
Logs.print("Result of enabling 3G: " + result, context); | |
usedFeature = result; | |
return result; | |
} | |
} | |
throw new IOException("Cannot establish 3G connectivity"); | |
} | |
protected void endSimultaneous3G() { | |
try { | |
Logs.print("Closing simultaneous 3G connection", context); | |
if (mConnMgr != null) { | |
mConnMgr.stopUsingNetworkFeature(usedFeature, | |
FEATURE_ENABLE_MMS); | |
} | |
} finally { | |
// releaseWakeLock(); | |
} | |
} | |
private static void createWakeLock() { | |
// Take a wake lock | |
// Create a new wake lock if we haven't made one yet. | |
if (mWakeLock == null) { | |
PowerManager pm = (PowerManager) context | |
.getSystemService(Context.POWER_SERVICE); | |
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, | |
"3F Connection"); | |
mWakeLock.setReferenceCounted(false); | |
} | |
} | |
private static void acquireWakeLock() { | |
if (mWakeLock == null) { | |
createWakeLock(); | |
} | |
Logs.print("Acquiring wakelock", context); | |
mWakeLock.acquire(); | |
} | |
private void releaseWakeLock() { | |
// Don't release the wake lock if it hasn't been created and acquired. | |
if (mWakeLock != null && mWakeLock.isHeld()) { | |
Logs.print("Releasing wakelock", context); | |
mWakeLock.release(); | |
} | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////// | |
import java.util.Date; | |
import java.util.Properties; | |
import javax.activation.CommandMap; | |
import javax.activation.DataHandler; | |
import javax.activation.DataSource; | |
import javax.activation.FileDataSource; | |
import javax.activation.MailcapCommandMap; | |
import javax.mail.BodyPart; | |
import javax.mail.MessagingException; | |
import javax.mail.Multipart; | |
import javax.mail.NoSuchProviderException; | |
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 MailSender extends javax.mail.Authenticator { | |
private String _user; | |
private String _pass; | |
private String[] _to; | |
private String _from; | |
private String _port; | |
private String _sport; | |
private String _host; | |
private String _subject; | |
private String _body; | |
private boolean _auth; | |
private boolean _debuggable; | |
private Multipart _multipart; | |
public MailSender() { | |
_host = ""; // default smtp server | |
_port = ""; // default smtp port | |
_sport = ""; // default socketfactory port | |
_user = ""; // username | |
_pass = ""; // password | |
_from = ""; // email sent from | |
_subject = ""; // email subject | |
_body = ""; // email body | |
_debuggable = false; // debug mode on or off - default off | |
_auth = true; // smtp authentication - default on | |
_multipart = new MimeMultipart(); | |
// There is something wrong with MailCap, javamail can not find a | |
// handler for the multipart/mixed part, so this bit needs to be added. | |
MailcapCommandMap mc = (MailcapCommandMap) CommandMap | |
.getDefaultCommandMap(); | |
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); | |
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); | |
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); | |
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); | |
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); | |
CommandMap.setDefaultCommandMap(mc); | |
} | |
public MailSender(String user, String pass) { | |
this(); | |
_user = user; | |
_pass = pass; | |
} | |
public MailSender(String user, String pass, String host, String port) { | |
this(); | |
_user = user; | |
_pass = pass; | |
_host = host; | |
_port = port; | |
_sport = port; | |
} | |
public boolean send() throws Exception { | |
Properties props = _setProperties(); | |
if (!_user.equals("") && !_pass.equals("") && _to.length > 0 | |
&& !_from.equals("") && !_subject.equals("") | |
&& !_body.equals("")) { | |
Session session = Session.getInstance(props, this); | |
MimeMessage msg = new MimeMessage(session); | |
msg.setFrom(new InternetAddress(_from)); | |
InternetAddress[] addressTo = new InternetAddress[_to.length]; | |
for (int i = 0; i < _to.length; i++) { | |
addressTo[i] = new InternetAddress(_to[i]); | |
} | |
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); | |
msg.setSubject(_subject); | |
msg.setSentDate(new Date()); | |
// setup message body | |
BodyPart messageBodyPart = new MimeBodyPart(); | |
messageBodyPart.setText(_body); | |
_multipart.addBodyPart(messageBodyPart); | |
// Put parts in message | |
msg.setContent(_multipart); | |
// send email | |
Transport.send(msg); | |
return true; | |
} else { | |
return false; | |
} | |
} | |
public void addAttachment(String filename) throws Exception { | |
BodyPart messageBodyPart = new MimeBodyPart(); | |
DataSource source = new FileDataSource(filename); | |
messageBodyPart.setDataHandler(new DataHandler(source)); | |
messageBodyPart.setFileName(filename); | |
_multipart.addBodyPart(messageBodyPart); | |
} | |
@Override | |
public PasswordAuthentication getPasswordAuthentication() { | |
return new PasswordAuthentication(_user, _pass); | |
} | |
private Properties _setProperties() { | |
Properties props = new Properties(); | |
props.put("mail.smtp.host", _host); | |
if (_debuggable) { | |
props.put("mail.debug", "true"); | |
} | |
if (_auth) { | |
props.put("mail.smtp.auth", "true"); | |
} | |
props.put("mail.smtp.starttls.enable", "true"); | |
props.put("mail.smtps.starttls.enable", "true"); | |
props.put("mail.smtp.port", _port); | |
props.put("mail.smtps.socketFactory.port", _sport); | |
props.put("mail.smtps.socketFactory.class", | |
"javax.net.ssl.SSLSocketFactory"); | |
props.put("mail.smtps.socketFactory.fallback", "false"); | |
return props; | |
} | |
// the getters and setters | |
public String getBody() { | |
return _body; | |
} | |
public void setBody(String _body) { | |
this._body = _body; | |
} | |
public void setTo(String[] toArr) { | |
// TODO Auto-generated method stub | |
this._to = toArr; | |
} | |
public void setFrom(String string) { | |
// TODO Auto-generated method stub | |
this._from = string; | |
} | |
public void setSubject(String string) { | |
// TODO Auto-generated method stub | |
this._subject = string; | |
} | |
// more of the getters and setters ….. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment