-
-
Save Ayesha17/a1739cd5735e4598b645e6553e6c6f6d to your computer and use it in GitHub Desktop.
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 android.accounts.Account; | |
import android.accounts.AccountManager; | |
import android.accounts.AccountManagerCallback; | |
import android.accounts.AccountManagerFuture; | |
import android.content.Intent; | |
import android.os.AsyncTask; | |
import android.os.Bundle; | |
import android.support.v4.app.FragmentActivity; | |
import android.util.Log; | |
import com.stackoverflow.ranjith.androidprojdel.backend.Constant; | |
public class AuthActivity extends FragmentActivity { | |
private static final int AUTHORIZATION_CODE = 1993; | |
private static final int ACCOUNT_CODE = 1601; | |
private AuthPreferences authPreferences; | |
private AccountManager accountManager; | |
private final String SCOPE = Constant.GMAIL_COMPOSE + " " + Constant.GMAIL_MODIFY + " " + Constant.MAIL_GOOGLE_COM; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
accountManager = AccountManager.get(this); | |
authPreferences = new AuthPreferences(this); | |
if (authPreferences.getUser() != null | |
&& authPreferences.getToken() != null) { | |
doCoolAuthenticatedStuff(); | |
} else { | |
chooseAccount(); | |
} | |
} | |
private void doCoolAuthenticatedStuff() { | |
//new senmailAsync().execute(); uncomment to send mail | |
} | |
private void chooseAccount() { | |
Intent intent = AccountManager.newChooseAccountIntent(null, null, | |
new String[]{"com.google"}, false, null, null, null, null); | |
startActivityForResult(intent, ACCOUNT_CODE); | |
} | |
private void requestToken() { | |
Account userAccount = null; | |
String user = authPreferences.getUser(); | |
for (Account account : accountManager.getAccountsByType("com.google")) { | |
if (account.name.equals(user)) { | |
userAccount = account; | |
break; | |
} | |
} | |
accountManager.getAuthToken(userAccount, "oauth2:" + SCOPE, null, this, | |
new OnTokenAcquired(), null); | |
} | |
/** | |
* call this method if your token expired, or you want to request a new | |
* token for whatever reason. call requestToken() again afterwards in order | |
* to get a new token. | |
*/ | |
private void invalidateToken() { | |
AccountManager accountManager = AccountManager.get(this); | |
accountManager.invalidateAuthToken("com.google", authPreferences.getToken()); | |
Log.v("ranjapp", "invalidating token............"); | |
authPreferences.setToken(null); | |
} | |
@Override | |
protected void onActivityResult(int requestCode, int resultCode, Intent data) { | |
super.onActivityResult(requestCode, resultCode, data); | |
if (resultCode == RESULT_OK) { | |
if (requestCode == AUTHORIZATION_CODE) { | |
requestToken(); | |
} else if (requestCode == ACCOUNT_CODE) { | |
String accountName = data | |
.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); | |
authPreferences.setUser(accountName); | |
// invalidate old tokens which might be cached. we want a fresh | |
// one, which is guaranteed to work | |
invalidateToken(); | |
requestToken(); | |
} | |
} | |
} | |
private class OnTokenAcquired implements AccountManagerCallback<Bundle> { | |
@Override | |
public void run(AccountManagerFuture<Bundle> result) { | |
try { | |
Bundle bundle = result.getResult(); | |
Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT); | |
if (launch != null) { | |
startActivityForResult(launch, AUTHORIZATION_CODE); | |
} else { | |
String token = bundle | |
.getString(AccountManager.KEY_AUTHTOKEN); | |
Log.v("ranjapp", "Getting new token............"); | |
authPreferences.setToken(token); | |
doCoolAuthenticatedStuff(); | |
} | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} | |
private class senmailAsync extends AsyncTask<Void, Void, Void> { | |
@Override | |
protected Void doInBackground(Void... params) { | |
GMailSender gMailSender = new GMailSender(); | |
gMailSender.sendMail("hi", "hi", authPreferences.getUser(), authPreferences.getToken(), "[email protected]"); | |
Log.v("ranjapp", "sent mail " + authPreferences.getUser() + " " + authPreferences.getToken()); | |
return null; | |
} | |
} | |
} |
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 android.content.Context; | |
import android.content.SharedPreferences; | |
import android.content.SharedPreferences.Editor; | |
import android.util.Log; | |
public class AuthPreferences { | |
private static final String KEY_USER = "userid"; | |
private static final String KEY_TOKEN = "mytoken"; | |
private SharedPreferences preferences; | |
public AuthPreferences(Context context) { | |
preferences = context.getSharedPreferences("authoris", Context.MODE_PRIVATE); | |
} | |
public void setUser(String user) { | |
Editor editor = preferences.edit(); | |
editor.putString(KEY_USER, user); | |
Log.v("ranjapp", "User is " + user); | |
editor.apply(); | |
} | |
public void setToken(String password) { | |
Editor editor = preferences.edit(); | |
editor.putString(KEY_TOKEN, password); | |
Log.v("ranjapp", "Password is " + password); | |
editor.apply(); | |
} | |
public String getUser() { | |
return preferences.getString(KEY_USER, null); | |
} | |
public String getToken() { | |
return preferences.getString(KEY_TOKEN, null); | |
} | |
} |
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
public static final String MAIL_GOOGLE_COM = "https://mail.google.com"; | |
public static final String GMAIL_COMPOSE = "https://www.googleapis.com/auth/gmail.compose"; | |
public static final String GMAIL_MODIFY = "https://www.googleapis.com/auth/gmail.modify"; |
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 android.util.Log; | |
import com.sun.mail.smtp.SMTPTransport; | |
import com.sun.mail.util.BASE64EncoderStream; | |
import java.util.Properties; | |
import javax.activation.DataHandler; | |
import javax.mail.Message; | |
import javax.mail.Session; | |
import javax.mail.URLName; | |
import javax.mail.internet.InternetAddress; | |
import javax.mail.internet.MimeMessage; | |
import javax.mail.util.ByteArrayDataSource; | |
public class GMailSender { | |
private Session session; | |
public SMTPTransport connectToSmtp(String host, int port, String userEmail, | |
String oauthToken, boolean debug) throws Exception { | |
Log.v("ranjapp", "came to connecttosmtp"); | |
Properties props = new Properties(); | |
props.put("mail.smtp.starttls.enable", "true"); | |
props.put("mail.smtp.starttls.required", "true"); | |
props.put("mail.smtp.sasl.enable", "false"); | |
//props.put("mail.imaps.sasl.mechanisms.oauth2.oauthToken", oauthToken); | |
session = Session.getInstance(props); | |
session.setDebug(debug); | |
final URLName unusedUrlName = null; | |
SMTPTransport transport = new SMTPTransport(session, unusedUrlName); | |
// If the password is non-null, SMTP tries to do AUTH LOGIN. | |
final String emptyPassword = null; | |
transport.connect(host, port, userEmail, emptyPassword); | |
Log.v("ranjapp", "came before gen response"); | |
byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail, oauthToken).getBytes(); | |
response = BASE64EncoderStream.encode(response); | |
Log.v("ranjapp", "came to call issuecommand " + transport.isConnected()); | |
Log.v("ranjapp", new String(response)); | |
transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235); | |
Log.v("ranjapp", "came after issue command"); | |
return transport; | |
} | |
public synchronized void sendMail(String subject, String body, String user, | |
String oauthToken, String recipients) { | |
try { | |
SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, user, oauthToken, true); | |
MimeMessage message = new MimeMessage(session); | |
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain")); | |
message.setSender(new InternetAddress(user)); | |
message.setSubject(subject); | |
message.setDataHandler(handler); | |
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); | |
smtpTransport.sendMessage(message, message.getAllRecipients()); | |
} catch (Exception e) { | |
Log.v("ranjith", e.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment