Skip to content

Instantly share code, notes, and snippets.

@vitaminac
Created July 14, 2018 00:26
Show Gist options
  • Save vitaminac/acf83dadfd6c37383e6f77312c95bfe1 to your computer and use it in GitHub Desktop.
Save vitaminac/acf83dadfd6c37383e6f77312c95bfe1 to your computer and use it in GitHub Desktop.
enviar los emailes con la cuenta de gmail
import com.sun.mail.smtp.SMTPTransport;
import com.sun.mail.util.BASE64EncoderStream;
import org.json.JSONObject;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
public class PasswordBaseEmail {
private static Properties props;
static {
props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
}
public static void main(String[] args) throws Exception {
final String receiver = "xxxxx@gmail.com";
// insecure acess
// activa la opcion de Aplicaciones menos seguras https://myaccount.google.com/lesssecureapps
String username = "xxxxx@gmail.com";
String password = "******";
sendEmailWithPass(username, password, receiver, "insecure-access");
// application-wide pass
// añade un app password https://security.google.com/settings/security/apppasswords, la opcion de verificacion en 2-pasos debe está activada
username = "xxxxx@gmail.com";
password = "******";
sendEmailWithPass(username, password, receiver, "application-wide pass");
// OAuth2
// obtiene credencial desde https://console.developers.google.com/apis/credentials Create credentials > OAuth client ID
final String clientID = "123456789...";
final String secret = "***...";
/*
paso-1 obtiene authenticated-code que usaremos en el paso 2
GET /o/oauth2/v2/auth?scope=https://mail.google.com/&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob&client_id=<client-id> HTTP/1.1
Host: accounts.google.com
Connection: close
paso-2 obtiene refresh-token
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 253
code=<authenticated-code>&client_id=<client-id>&client_secret=<secret>&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code
*/
final String refreshToken = "***...";
sendMailWithOAuth(username, fetchAccessToken(clientID, secret, refreshToken), receiver);
}
/*
paso 3 - obtiene access-token
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 206
client_id=<client-id>&client_secret=<secret>&refresh_token=<refresh-token>&grant_type=refresh_token
*/
private static String fetchAccessToken(String clientID, String secret, String refreshToken) throws IOException {
Map<String, Object> params = new LinkedHashMap<>();
params.put("grant_type", "refresh_token");
params.put("client_id", clientID);
params.put("client_secret", secret);
params.put("refresh_token", refreshToken);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
URL url = new URL("https://accounts.google.com/o/oauth2/token");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.getOutputStream().write(postDataBytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
return json.getString("access_token");
}
private static MimeMessage buildMessage(Session session, String username, String receiver, String content) throws Exception {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
message.setSubject("Test");
message.setContent("<h1>" + content + "</h1>", "text/html");
return message;
}
private static void sendEmailWithPass(final String username, final String password, final String receiver, String content) throws Exception {
final Properties clone = (Properties) props.clone();
clone.put("mail.smtp.auth", "true");
Session session = Session.getInstance(clone, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
final MimeMessage message = buildMessage(session, username, receiver, content);
Transport.send(message);
System.out.println("Done " + content);
}
private static void sendMailWithOAuth(String username, String accessToken, String receiver) throws Exception {
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
final MimeMessage message = buildMessage(session, username, receiver, "OAuth");
SMTPTransport transport = new SMTPTransport(session, null);
transport.connect("smtp.gmail.com", username, null);
transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream
.encode(String.format("user=%s\1auth=Bearer %s\1\1", username, accessToken).getBytes())), 235);
transport.sendMessage(message, message.getAllRecipients());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment