I'm using JavaMail API to notify the administrator when there's data insertion in database
This works fine. The admin receives the notification of data entry.
However, I also need to notify the client by sending him a confirmation at the same time, but it does not work. The customer does not receive any confirmation. I also want to paste the confirmation number in the subject. Could it be related to port conflict?
EmailAdmin.sendEmail(to, subject, body);
EmailCustomer.sendEmail(EM, subjectsub, bodybod, CN);
EmailAdmin.java
package session;
import java.util.Date;
import java.util.Properties;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
#Stateless
#LocalBean
public class EmailAdmin {
private final int port = 465;
private final String host = "smtp.server.com";
private final String from = "admin#domain.com";
private final boolean auth = true;
private final String username = "admin#domain.com";
private final String password = "password";
private final Protocol protocol = Protocol.SMTPS;
private final boolean debug = true;
public void sendEmail(String to, String subject, String body) {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
switch (protocol) {
case SMTPS:
props.put("mail.smtp.ssl.enable", true);
break;
case TLS:
props.put("mail.smtp.starttls.enable", true);
break;
}
Authenticator authenticator = null;
if (auth) {
props.put("mail.smtp.auth", true);
authenticator = new Authenticator() {
private final PasswordAuthentication pa = new PasswordAuthentication(username, password);
#Override
public PasswordAuthentication getPasswordAuthentication() {
return pa;
}
};
}
Session session = Session.getInstance(props, authenticator);
session.setDebug(debug);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject);
message.setSentDate(new Date());
message.setText(body);
Transport.send(message);
} catch (MessagingException ex) {
}
}
}
EmailCustomer.java
package session;
import java.util.Date;
import java.util.Properties;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
#Stateless
#LocalBean
public class EmailCustomer {
private final int port = 465;
private final String host = "smtp.server.com";
private final String from = "admin#domain.com";
private final boolean auth = true;
private final String username = "admin#domain.com";
private final String password = "password";
private final Protocol protocol = Protocol.SMTPS;
private final boolean debug = true;
public void sendEmail(String EM, String subjectsub, String bodybod, String CN) {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
switch (protocol) {
case SMTPS:
props.put("mail.smtp.ssl.enable", true);
break;
case TLS:
props.put("mail.smtp.starttls.enable", true);
break;
}
Authenticator authenticator = null;
if (auth) {
props.put("mail.smtp.auth", true);
authenticator = new Authenticator() {
private final PasswordAuthentication pa = new PasswordAuthentication(username, password);
#Override
public PasswordAuthentication getPasswordAuthentication() {
return pa;
}
};
}
Session session = Session.getInstance(props, authenticator);
session.setDebug(debug);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(EM)};
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject, CN);
message.setSentDate(new Date());
message.setText(body);
Transport.send(message);
} catch (MessagingException ex) {
}
}
}
Related
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.
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.
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.
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);
}
}
}
I am sending an email using the Java mail api. And it works fine when I send an email to myself from my own account. But when I try to send an email to a different account it gives me an authentication exception. Here is my code:
package nl.cofely.MailHandler;
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
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 Mail extends javax.mail.Authenticator {
private String _user;
private String[] _to;
private String _from;
private String _pass;
private String _port;
private String _sport;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private boolean testMessageSend;
private Multipart _multipart;
static Mail instance;
private Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_subject = "Person in trouble !"; // email subject
_body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a
// handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap
.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public static Mail getInstance(){
if(instance == null){
instance = new Mail();
}
return instance;
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if (_debuggable) {
props.put("mail.debug", "true");
}
if (_auth) {
props.put("mail.smtp.auth", "true");
}
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
// the getters and setters
public String getBody() {
return _body;
}
public void setBody(String _body) {
_body = _body + " gebruiker: " + _from;
this._body = _body;
}
// more of the getters and setters …..
public boolean send() throws Exception {
Properties props = _setProperties();
if (!_user.equals("") && !_pass.equals("") && _to.length > 0
&& !_from.equals("") && !_subject.equals("")
&& !_body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
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(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
if(testMessageSend){
_multipart.removeBodyPart(0);
}
_multipart.addBodyPart(messageBodyPart,0);
System.out.println(_multipart.getBodyPart(0));
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public boolean sendTestMail() throws Exception{
setSubject("Testing mail configuration!");
setBody("Dit is een email voor het testen van de email configuratie ");
testMessageSend = send();
setBody("");
return testMessageSend;
}
public void setFrom(String _from){
this._from = _from;
}
public String getFrom(){
return _from;
}
public void setPass(String _pass){
this._pass = _pass;
}
public String getPass(){
return _pass;
}
public void setSubject(String _subject){
this._subject = _subject;
}
public String getSubject(){
return _subject;
}
public void setUser(String _user){
this._user = _user;
}
public String getUser(){
return _user;
}
public void updateUserInfo(String[] _to, String _from, String _pass){
this._to = _to;
this._from = _from;
this._pass = _pass;
this._user = _to[0].substring(0, _to[0].lastIndexOf("#"));
}
}
Can anyone tell what is going on here? Thanks
Try something like this:
public int sendMail(String reciever_email, String subject, String body) {
final String username = "YOUR USER EMAIL";
final String password = "PASSWORD";
Properties props = new Properties();
props.put("mail.smtp.user", username);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallbac k", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(reciever_email));
message.setSubject(subject);
message.setText(body);
Multipart multipart = new MimeMultipart("related");
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<html>HELLO</html>", "text/html");
multipart.addBodyPart(htmlPart);
message.setContent(multipart);
Transport.send(message);
return 1;
} catch (Exception e) {
return 0;
}
}