Android - keep javax.mail.Session reference across app life - java

here is my state I am working in app that authenticate user with our company email and password
I created class to handle authenticate action , I need keep reference of my session to be able to send email .
my tries :
1- save username , password and this is not secure.
2- save session via application instance but this remove when app closed.
any suggestion thank you in advance
import javax.activation.DataHandler;
import javax.mail.AuthenticationFailedException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
/**
* Created by mina on 8/28/2016.
*/
public class PMailSender {
private String username;
private String password;
private String mailhost = "OURHOSt";
private String stmp_port= "465";
private Session session;
static {
Security.addProvider(new JSSEProvider());
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public PMailSender(){
}
public PMailSender(String username, String password) {
this.username = username;
this.password = password;
Properties prop = new Properties();
prop.setProperty("mail.transport.protocol" , "smtp");
prop.setProperty("mail.host" , mailhost);
prop.setProperty("mail.smtp.quitwait" , "false");
prop.put("mail.smtp.auth" , "true");
prop.put("mail.smtp.port" , stmp_port);
prop.put("mail.smtp.socketFactory.port" , stmp_port);
prop.put("mail.smtp.socketFactory.class" , "javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.fallback","false");
session = Session.getInstance(prop , new PMailAuthenticator(username,password ));
session.setDebug(true);
}
public boolean ValidateCredential(){
try {
Transport tr= session.getTransport();
tr.connect(mailhost , username , password);
Store mStore=session.getStore();
tr.close();
}catch (AuthenticationFailedException e){
return false;
}catch (MessagingException e){
throw new RuntimeException("validate error " , e);
}
return true;
}
public synchronized void SendMail (String subject , String body
, String sender , String recipients ) throws MessagingException {
MimeMessage message = new MimeMessage(session);
DataHandler handler= new DataHandler(new ByteArrayDataSource(body.getBytes() , "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if(recipients.indexOf(",") > 0)
message.setRecipients(Message.RecipientType.TO ,InternetAddress.parse(recipients) );
else
message.setRecipient(Message.RecipientType.TO , new InternetAddress(recipients));
Transport.send(message);
}
}

Related

Send Email in Java Fxml Issue

I met a problem when I try to send email in Java by using Gmail SMTP.
Once I started the email feature, there will be a email window pop out:
The user will key in the subject and email content and then send an email by clicking the button.
There will be two errors come out once the user clicked the button.
How can I fix the problem?
The errors are:
java.lang.reflect.InvocationTargetException
java.lang.VerifyError: (class: com/sun/mail/handlers/handler_base, method: getTransferData signature: (Ljavax/activation/ActivationDataFlavor;Ljavax/activation/DataSource;)Ljava/lang/Object;) Incompatible argument to function
My code is shown below:
package seedu.address.ui.email;
import java.util.Properties;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import seedu.address.commons.core.LogsCenter;
public class EmailWindowController {
private final Logger logger = LogsCenter.getLogger(EmailWindowController.class);
private String password;
private String from;
private String to;
#FXML
private Button sendButton;
#FXML
private Label senderEmailAddress;
#FXML
private Label receiverEmailAddress;
#FXML
private TextField subjectTestField;
#FXML
private TextArea emailContentArea;
#FXML
void handleButtonAction(ActionEvent event) {
if (event.getSource() == sendButton) {
String subject = subjectTestField.getText();
String content = emailContentArea.getText();
//sendEmail(subject, content);
sendSimpleEmail(subject, content);
}
}
void initData(String from, String password, String to) {
senderEmailAddress.setText(from);
receiverEmailAddress.setText(to);
this.password = password;
this.from = from;
this.to = to;
}
private void sendSimpleEmail(String subject, String content) {
String host = "smtp.gmail.com";
final String senderAddress = from;
final String senderPassword = this.password;
final String toAddress = this.to;
//setup mail server
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", senderAddress);
props.put("mail.smtp.password", senderPassword);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage m = new MimeMessage(session);
try {
m.setFrom(new InternetAddress(senderAddress));
m.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress));
m.setSubject(subject);
m.setText(content);
//send mail
Transport transport = session.getTransport("smtp");
transport.connect(host, senderAddress, senderPassword);
transport.sendMessage(m, m.getAllRecipients());
transport.close();
//sentBoolValue.setVisible(true);
System.out.println("Message sent!");
} catch (MessagingException ae) {
ae.printStackTrace();
}
}
/*
private void sendEmail(String subject, String content) {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
Session session = Session.getInstance(properties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
Message message = prepareMessage(session, from, to, subject, content);
try {
Transport.send(message);
} catch (MessagingException e) {
logger.info(" -------- Email Send Process Failed -------- ");
e.printStackTrace();
}
}
private Message prepareMessage(Session session, String sender,
String receiver, String subject,
String content) {
MimeMessage mimeMessage = new MimeMessage(session);
try {
// Create Email
mimeMessage.setFrom(new InternetAddress(sender));
mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiver));
mimeMessage.setSubject(subject);
mimeMessage.setText(content);
return mimeMessage;
} catch (MessagingException e) {
logger.info(" -------- Email Prepare Process Failed -------- ");
e.printStackTrace();
}
return mimeMessage;
}
*/
}
I don't know why the error occurs but I see two possible issue why it isn't working.
You ask for a authentication through SMTP
props.put("mail.smtp.auth", "true");
without creating a real auth like
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Why do you get your properties from System instead generating one ?
Properties props = System.getProperties(); instead of Properties props = new Properties();
Replace
implementation 'com.sun.mail:android-mail:*'
implementation 'com.sun.mail:android-activation:*'
on
implementation 'com.sun.mail:jakarta.mail:*'
implementation 'com.sun.activation:jakarta.activation:*'
And create app password here:
https://myaccount.google.com/security -> App passwords

how to send email from using outlook using a java api

I am using the below code to send email from outlook using java. But getting the error.
CODE:
public static void mail (){
// TODO Auto-generated method stub
//String host="POKCPEX07.corp.absc.local";
String host="POKCPEX07.corp.absc.local";
final String user="satpal.gupta#accenture.com";
String to="satpal.gupta#accenture.com";
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.port", "587");
Session session=Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("SGupta#amerisourcebergen.com","******");
}
});
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.saveChanges();
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Test mail");
message.setText("This is test mail.");
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
}
catch (MessagingException e) {e.printStackTrace();}
}
}
ERROR:
javax.mail.MessagingException: Could not connect to SMTP host: POKCPEX07.corp.absc.local, port: 587;
nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1227)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:322)
at javax.mail.Service.connect(Service.java:258)
at javax.mail.Service.connect(Service.java:137)
at javax.mail.Service.connect(Service.java:86)
at javax.mail.Transport.send0(Transport.java:150)
at javax.mail.Transport.send(Transport.java:80)
at TestEmail.mail(TestEmail.java:50)
at TestEmail.main(TestEmail.java:16)
package com.sendmail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendAttachmentInEmail {
private static final String SERVIDOR_SMTP = "smtp.office365.com";
private static final int PORTA_SERVIDOR_SMTP = 587;
private static final String CONTA_PADRAO = "xxxx#xxx.com"; //Cofig Mail Id
private static final String SENHA_CONTA_PADRAO = "XYZ"; // Password
private final String from = "xxxx#xxx.com";
private final String to = "xxxx#xxx.com";
private final String subject = "Teste";
private final String messageContent = "Teste de Mensagem";
public void sendEmail() {
final Session session = Session.getInstance(this.getEmailProperties(), new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(CONTA_PADRAO, SENHA_CONTA_PADRAO);
}
});
try {
final Message message = new MimeMessage(session);
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setFrom(new InternetAddress(from));
message.setSubject(subject);
message.setText(messageContent);
message.setSentDate(new Date());
Transport.send(message);
} catch (final MessagingException ex) {
System.out.println(" "+ex);
}
}
public Properties getEmailProperties() {
final Properties config = new Properties();
config.put("mail.smtp.auth", "true");
config.put("mail.smtp.starttls.enable", "true");
config.put("mail.smtp.host", SERVIDOR_SMTP);
config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
return config;
}
public static void main(final String[] args) {
new SendAttachmentInEmail().sendEmail();
}
}
As posted by you in comments above, it looks like your SMTP is not configured and by looking your exception - you are using gmail.
Follow this link to configure your SMTP.

Java ssl email sends to spam and not inbox

import java.util.Properties;
import javax.mail.Authenticator;
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;
public class SendEmail {
private static String hostname;
private static String username;
private static String password;
private static String sendTo;
private static String sentFrom;
private static String emailBody;
// sendSLLEmail()
public String sendSLLEmail(String hostname, String username,
String password, String sendTo, String sentFrom,String subject, String emailBody) {
try {
SendEmail.hostname = hostname;
SendEmail.username = username;
SendEmail.password = password;
SendEmail.sendTo = sendTo;
SendEmail.sentFrom = sentFrom;
SendEmail.emailBody = emailBody;
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SendEmail.hostname);
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(subject);
message.setContent(SendEmail.emailBody, "text/html; charset=utf-8");
message.setFrom(new InternetAddress(SendEmail.sentFrom));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(SendEmail.sendTo));
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
return "1";
} catch (Exception e) {
e.printStackTrace();
return "-1";
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String usernameTest = SendEmail.username;
String passwordTest = SendEmail.password;
return new PasswordAuthentication(usernameTest, passwordTest);
}
}
}
When I use this code, I pass values to it as parameters. The e-mail gets sent and works well, but always lands up in my clients spam folder can anyone tell me how I can prevent this ?
When I run this code I use my own mail server, so I would pass all the correct parameters to the code then it connects to my mail server and then gets mailed to spam.

How to resolve javax.mail.AuthenticationFailedException issue

This program attempts to send e-mail but throws a run time exception:AuthenticationFailedException I have referred the stackoverflow quetion and answer also same thing I have implemented but still I am getting exception like this could any one plz resolve this issue.
Exception
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:267)
at javax.mail.Service.connect(Service.java:137)
at javax.mail.Service.connect(Service.java:86)
at javax.mail.Transport.send0(Transport.java:150)
at javax.mail.Transport.send(Transport.java:80)
at com.treamis.transport.vehicle.javaMail.send(javaMail.java:81)
at com.treamis.transport.vehicle.MysqlBackup.backupDataWithDatabase(Mysq
lBackup.java:97)
at com.treamis.transport.vehicle.MysqlBackup.run(MysqlBackup.java:118)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Sms sent xl sheet is generated is generated
java Mail code
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
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 javaMail {
private String SMTP_PORT = "465";
private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
private String SMTP_HOST_NAME = "smtp.gmail.com";
private Properties smtpProperties;
public javaMail() {
initProperties();
}
private void initProperties() {
smtpProperties = new Properties();
smtpProperties.put("mail.smtp.host", SMTP_HOST_NAME);
smtpProperties.put("mail.smtp.auth", "true");
smtpProperties.put("mail.debug", "true");
smtpProperties.put("mail.smtp.port", SMTP_PORT);
smtpProperties.put("mail.smtp.socketFactory.port", SMTP_PORT);
smtpProperties.put("mail.smtp.socketFactory.class", SSL_FACTORY);
smtpProperties.put("mail.smtp.socketFactory.fallback", "false");
}
public String send(String[] to, final String from, final String pwd, String subject, String body) {
javaMail tjm = new javaMail();
try {
Properties props = tjm.getSmtpProperties();
// -- Attaching to default Session, or we could start a new one --
// Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(from, pwd);
// }
// });
Session session = Session.getInstance(props, new GMailAuthenticator(from, pwd));
// Session session = Session.getInstance(props, new javax.mail.Authenticator() {
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(userName, password);
// }
//});
Message msg = new MimeMessage(session);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Test mail one");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(body);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(body);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
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(Message.RecipientType.TO, addressTo);
// msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
msg.setSubject(subject);
msg.setSentDate(new Date());
Transport.send(msg);
System.out.println("Message sent OK.");
return "success";
} catch (Exception ex) {
ex.printStackTrace();
ex.getMessage();
}
return null;
}
public Properties getSmtpProperties() {
return smtpProperties;
}
public void setSmtpProperties(Properties smtpProperties) {
this.smtpProperties = smtpProperties;
}
}
GMailAuthenticator code
*/
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
class GMailAuthenticator extends Authenticator {
String user;
String pw;
public GMailAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
AuthenticationFailedException means the server thinks you gave it the wrong username or password. You're going to say "of course I didn't give it the wrong username or password, I'm not that stupid!" Well, the server disagrees with you.
Try turning on JavaMail session debugging, the protocol trace might provide additional clues as to what's going wrong. You might also need to set the "mail.debug.auth" property to "true" to get additional details about the login process.
Also, see the JavaMail FAQ for some common mistakes in your code.
And make sure there's no anti-virus or firewall that's intercepting your attempts to connect to the server.

unable to send mail from java program authentication fail errorauthentication fail error

I am unable to send mail -- the program is throwing an authentication error
package com.gmc.registration.util;
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MailWithAttachement {
private String sender;
private String addressee;
private String subject;
private String nameOfAttachedFile;
private String filePath;
private String body;
private String contentType;
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private transient String SMTP_AUTH_USER = "";
private transient String SMTP_AUTH_PWD = "";
public MailWithAttachement(final String sender, final String addressee, final String subject, final String nameOfAttachedFile, final String filePath, final String body, final String contentType) {
this.sender = sender;
this.addressee = addressee;
this.subject = subject;
this.nameOfAttachedFile = nameOfAttachedFile;
this.filePath = filePath;
this.body = body;
this.contentType = contentType;
}
public int send() {
int flag = 0;
final ResourceBundle resource = ResourceBundle.getBundle("com.gmc.student.resourseprop.student");
final Properties mailServerProperties = new Properties();
mailServerProperties.put("mail.smtp.host", resource.getString("mail.smtp.host"));
mailServerProperties.put("mail.smtp.port", resource.getString("mail.smtp.port"));
mailServerProperties.put("mail.smtp.auth", resource.getString("mail.smtp.auth"));
mailServerProperties.put("mail.smtp.sendpartial", resource.getString("mail.smtp.sendpartial"));
final Authenticator auth = new SMTPAuthenticator(resource.getString("mail.smtp.username"), resource.getString("mail.smtp.password"));
final Session session = Session.getDefaultInstance(mailServerProperties, auth);
// final Session session = Session.getInstance(mailServerProperties);
// final Session session = Session.getDefaultInstance(mailServerProperties);
final MimeMessage messageToSend = new MimeMessage(session);
try {
messageToSend.setFrom(new InternetAddress(this.sender));
messageToSend.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addressee));
messageToSend.setSubject(this.subject);
final BodyPart bodyText = new MimeBodyPart();
bodyText.setContent(this.body, this.contentType);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyText);
if (this.nameOfAttachedFile != null && this.filePath != null && !"".equals(this.nameOfAttachedFile) && !"".equals(this.filePath)) {
addAttachments(multipart);
}
messageToSend.setContent(multipart);
Transport.send(messageToSend);
flag = 1;
} catch (MessagingException exception) {
} catch (Exception excp) {
}
return flag;
}
private void addAttachments(final Multipart multipart) {
try {
final BodyPart attachment = new MimeBodyPart();
DataSource dataSource = new FileDataSource(this.filePath + this.nameOfAttachedFile);
attachment.setDataHandler(new DataHandler(dataSource));
attachment.setFileName(this.nameOfAttachedFile);
multipart.addBodyPart(attachment);
} catch (MessagingException excp) {
}
}
public static boolean emailvalidation(final String email) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private class SMTPAuthenticator extends javax.mail.Authenticator {
private SMTPAuthenticator(final String username, final String password) {
SMTP_AUTH_USER = username;
SMTP_AUTH_PWD = password;
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
}
}
public static void main(String[] args) {
new MailWithAttachement("ash.k#test.com", "xxh.k#test.com", "sub", null, null, "<h1>This is a test</h1>"
+ "", "text/html").send();
}
}
prop file
mail.attachement.filepath=E:/test/attchedFiles/
mail.smtp.host=mail.test.com
mail.smtp.port=587
mail.smtp.username=ash.t
mail.smtp.password=123456
mail.smtp.auth=true
mail.smtp.sendpartial=true
As you haven't given a verbose of the exception, i'm posting my module that i have been using in production, it seems to work pretty well with gmail accounts.
/**
GmailSmtpSSL emailNotify = new GmailSmtpSSL(cred[ID], cred[PASS]);
emailNotify.sendMailTo("self","Testing AlfaDX Gmail module", "Yes it works");
**/
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GmailSmtpSSL {
GmailSmtpSSL(String username,String password) {
usern = username;
pass = password;
setDebugMsg("Setting user name to : "+usern);
setDebugMsg("Using given password : "+pass);
props = new Properties();
setDebugMsg("Setting smtp server: smtp.gmail.com");
setDebugMsg("Using SSL at port 465 auth enabled");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.user", usern);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
//props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SMTPAuthenticator auth = new SMTPAuthenticator();
session = Session.getDefaultInstance(props, auth);
session.setDebug(true);
setDebugMsg("Session initialization complete");
}
public void destroy() {
props.clear();
props = null;
usern = null;
pass = null;
session = null;
}
public void sendMailTo(String to, String sub, String body)
throws MessagingException {
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss a");
String dateToday = formatter.format(currentDate.getTime()).toLowerCase();
if (to.equals("self"))
to = usern;
setDebugMsg("Composing message: To "+to);
setDebugMsg("Composing message: Subject "+sub);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(usern));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("PinguBot: "+dateToday+" "+sub);
message.setText(body);
setDebugMsg("Attempting to send...");
Transport transport = session.getTransport("smtps");
transport.connect("smtp.gmail.com", 465, usern, pass);
Transport.send(message);
transport.close();
}
catch(MessagingException me) {
setDebugMsg(me.toString());
throw new MessagingException(me.toString());
}
setDebugMsg("Mail was send successfully");
}
public String getDebugMsg() {
String msg = new String(debugMsg);
debugMsg = " ";
return msg;
}
private static void setDebugMsg(String msg) {
debugMsg += msg + "\n";
System.out.println(msg);
}
private static String debugMsg = "";
private String usern;
private String pass;
private Session session;
private static Properties props;
private class SMTPAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(usern, pass);
}
}
}

Categories