Skip to content

Instantly share code, notes, and snippets.

@NSergeyI
Created August 14, 2019 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NSergeyI/92fe93b5f484726c59986fd387581209 to your computer and use it in GitHub Desktop.
Save NSergeyI/92fe93b5f484726c59986fd387581209 to your computer and use it in GitHub Desktop.
gmail
package server.service;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.*;
import com.google.api.services.gmail.model.Message;
import domain.AppUser;
import java.io.*;
import java.util.*;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import server.auth.CredentialManager;
import server.utils.PdfUtils;
/* author: Ivan Silaev */
public class EmailService {
private static final Logger LOG = Logger.getLogger(EmailService.class.getName());
private static final String EMAIL_VERIFICATION =
"(?<name>[\\w.]+)\\@(?<domain>\\w+\\.\\w+)(\\.\\w+)?";
private static final int MESSAGE_PAGING_COUNT = 2;
private static Boolean INCLUDE_TRASH_SPAM = false;
private static String nextPageToken = "";
public static void sendMailThroughGoogle(
AppUser from, List<String> to, String subject, String body, boolean sendPdf)
throws IOException, MessagingException {
try {
// if (!ServerUtils.isProduction()) to =
// Collections.singletonList("snikitin@akolchin.com");
to = Collections.singletonList("snikitin@akolchin.com");
Gmail service = CredentialManager.buildGmailService(from);
Message message = encodeMimeMessageToMessage(getMimeMessage(from, to, subject, body, sendPdf));
LOG.info("Sending email via Gmail API to:" + to.toString() + " from: " + from.getEmail());
service.users().messages().send("me", message).execute();
} catch (IOException | MessagingException e) {
LOG.warning(
"Error has occurred when trying to send message \n"
+ "from:"
+ from.getEmail()
+ "\n"
+ "to: "
+ to.toString()
+ "\n"
+ "ERROR: "
+ e.getMessage());
throw e;
}
}
public static MimeMessage findAbuseMessageReply(AppUser who) {
try {
Gmail service = CredentialManager.buildGmailService(who);
MimeMessage message =
findMessage(
service,
getMessagesIds(service),
Collections.singletonList("dlukashov@akolchin.com"));
if (message == null) {
for (int i = 0; i < MESSAGE_PAGING_COUNT; i++) {
if (nextPageToken != null) {
List<String> messagesIdsFromPage = getMessagesIdsFromPage(service, nextPageToken);
MimeMessage replyMessage =
findMessage(
service,
messagesIdsFromPage,
Collections.singletonList("dlukashov@akolchin.com"));
if (replyMessage != null) return replyMessage;
}
}
}
return message;
} catch (IOException | MessagingException e) {
e.printStackTrace();
}
return null;
}
private static MimeMessage findMessage(
Gmail service, List<String> messagesIds, List<String> possibleReplyEmails)
throws IOException, MessagingException {
Properties properties = new Properties();
Session session = Session.getDefaultInstance(properties, null);
for (String id : messagesIds) {
Message message = service.users().messages().get("me", id).setFormat("raw").execute();
byte[] decode = java.util.Base64.getUrlDecoder().decode(message.getRaw());
MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(decode));
InternetAddress[] fromAddresses = (InternetAddress[]) email.getFrom();
for (InternetAddress from : fromAddresses) {
for (String s : possibleReplyEmails) {
if (s.equals(from.getAddress())) return email;
}
}
}
return null;
}
private static List<String> getMessagesIdsFromPage(Gmail service, String pageToken)
throws IOException {
List<String> messageIds = new ArrayList<>();
ListMessagesResponse me =
service
.users()
.messages()
.list("me")
.setPageToken(pageToken)
.setIncludeSpamTrash(INCLUDE_TRASH_SPAM)
.execute();
List<Message> messages = me.getMessages();
messages.forEach(message -> messageIds.add(message.getId()));
nextPageToken = me.getNextPageToken();
return messageIds;
}
private static List<String> getMessagesIds(Gmail service) throws IOException {
List<String> messageIds = new ArrayList<>();
ListMessagesResponse me =
service.users().messages().list("me").setIncludeSpamTrash(INCLUDE_TRASH_SPAM).execute();
List<Message> messages = me.getMessages();
messages.forEach(message -> messageIds.add(message.getId()));
nextPageToken = me.getNextPageToken();
return messageIds;
}
private static Message encodeMimeMessageToMessage(MimeMessage mimeMessage)
throws IOException, MessagingException {
Message message = new Message();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
mimeMessage.writeTo(buffer);
Base64 base64 = new Base64(); //
byte[] bytes = buffer.toByteArray();
String encodeEmail = base64.encodeToString(bytes);
encodeEmail = encodeEmail.replace('/', '_').replace('+', '-');
message.setRaw(encodeEmail);
return message;
}
private static MimeMessage getMimeMessage(
AppUser from, List<String> to, String subject, String body) throws MessagingException {
Properties properties = new Properties();
Session session = Session.getDefaultInstance(properties);
MimeMessage email = new MimeMessage(session);
email.addRecipients(javax.mail.Message.RecipientType.TO, convertEmailsToInternetAdresses(to));
email.setFrom(new InternetAddress(from.getEmail()));
email.setSubject(subject);
email.setText(body);
return email;
}
private static MimeMessage getMimeMessage(
AppUser from, List<String> to, String subject, String body, boolean sendPdf) throws MessagingException, IOException {
MimeMessage email = getMimeMessage(from, to, subject, body);
if (sendPdf) {
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
ByteArrayOutputStream out = new ByteArrayOutputStream();
PDDocument pdf = PdfUtils.getPDF();
pdf.save(out);
pdf.close();
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
ByteArrayDataSource source = new ByteArrayDataSource(in, "application/pdf");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("test1.pdf");
in.close();
multipart.addBodyPart(messageBodyPart);
email.setContent(multipart);
}
return email;
}
private static InternetAddress[] convertEmailsToInternetAdresses(List<String> emails)
throws AddressException {
for (String s : emails) {
if (s.contains("abuse")) {
return new InternetAddress[]{new InternetAddress(s)};
}
}
InternetAddress[] internetAddress = new InternetAddress[emails.size()];
for (int i = 0; i < internetAddress.length; i++) {
internetAddress[i] = new InternetAddress(emails.get(i));
}
return internetAddress;
}
public static void sendLetterSMTP(String textBody) {
String from = "------------";
String pass = "-------";
String[] to = {"-----------"};
String subject = "Java send mail example";
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", 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];
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
for (int i = 0; i < toAddress.length; i++) {
message.addRecipient(javax.mail.Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(textBody);
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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment