Skip to content

Instantly share code, notes, and snippets.

@RazorSh4rk
Created December 16, 2018 10:43
Show Gist options
  • Save RazorSh4rk/9ab62261d82fa54fb69f41468c1b1c63 to your computer and use it in GitHub Desktop.
Save RazorSh4rk/9ab62261d82fa54fb69f41468c1b1c63 to your computer and use it in GitHub Desktop.
Send an email with java without reading 100s of how-tos
package Control;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.MimeMessage;
public class Email {
public static void send(String to, String sub, String msg, final String user, final String pass) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(sub);
message.setText(msg);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment