Custom JMail delivery with properties from service - java

I know this issue is old, but I didn't find any solution for SimpleMailMessage with properties added in the class and not in the xml. There is no exeption after my app starts, its simply not sending mail. The method CustomMailDeliveryImpl.sendMail() is trigered from Controlller. I cant find a mistake.
#Component("CustomMailDelivery")
public class CustomMailDeliveryImpl implements CustomMailDelivery {
protected static Logger logger = Logger.getLogger(CustomMailDeliveryImpl.class);
private EmployeeService employeeService;
private String username = "* * *#gmail.com";
private String password = "* * *";
private JavaMailSenderImpl sender = new JavaMailSenderImpl();
#Autowired
public void setSender(JavaMailSenderImpl sender) {
this.sender = sender;
}
#Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
/**
* #param from - must contain address of sender,
* #param to - must contain address of target,
* #param subject - must be included with short description,
* #param body - main message of mail.
* #throws RuntimeException if any param is empty.
*/
public void sendMail(String from, String to, String subject, String body) {
// selecting settings from DB
SystemSettingsModel settingsModel = employeeService.getSettingsByName("default");
// defining settings
sender.setHost(settingsModel.getSmtpServerAddress());
sender.setPort(settingsModel.getSmtpServerPort());
sender.setUsername(username);
sender.setPassword(password);
// defining SMTP properties
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.debug", "1");
Session session = Session.getDefaultInstance(properties, null);
sender.setSession(session);
// initiating mail
SimpleMailMessage simpleMessage = new SimpleMailMessage();
try {
if (from != null && to != null) {
if (subject != null && body != null) {
simpleMessage.setFrom(from);
simpleMessage.setTo(to);
simpleMessage.setSubject(subject);
simpleMessage.setText(body);
sender.send(simpleMessage);
logger.debug("Mail has been sent successfully");
} else {
throw new MessagingException("Subject and message of mail is empty!");
}
} else {
throw new MessagingException("Address of object and target is empty!");
}
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Any help appreciated !!!!

I finally managed to overcome this issue and I did found the solution! With this way? you can pass properties from page configuration or DAO Service!
#Component("CustomMailDeliveryImpl")
public class CustomMailDeliveryImpl implements CustomMailDelivery {
private EmployeeService employeeService;
private Transport transport;
private String username = "***#gmail.com";
private String password = "***";
private SystemSettingsModel settingsModel;
private Session session;
private MimeMessage message;
private InternetAddress fromAddress, toAddress;
private Properties properties;
#Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
public void sendMail(String from, String to, String subject, String body) throws SendFailedException {
settingsModel = employeeService.getSettingsByName("default");
// defining properties
properties = new Properties();
properties.put("mail.smtp.host", settingsModel.getSmtpServerAddress());
properties.put("mail.smtp.port", settingsModel.getSmtpServerPort());
properties.put("mail.smtp.user", username);
properties.put("mail.smtp.password", password);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// InternetAddress initialisation
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
// new Authenticator session
session = (javax.mail.Session) Session.getDefaultInstance(properties, null);
} catch (AddressException e) {
throw new RuntimeException();
}
// executing mail sending
try {
if (from != null && to != null) {
if (subject != null && body != null) {
// defining message
message = new MimeMessage(session);
message.setFrom(fromAddress);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(body);
message.setSentDate(new Date());
message.setHeader("MIME-Version" , "1.0" );
message.setHeader("Content-Type" , "text/html" );
// Transport initialisation
if (transport == null) {
transport = session.getTransport("smtp");
if (!transport.isConnected())
transport.connect(settingsModel.getSmtpServerAddress(),
settingsModel.getSmtpServerPort(), username, password);
}
transport.sendMessage(message, message.getAllRecipients());
} else {
throw new MessagingException("Subject and message of mail is empty!");
}
} else {
throw new MessagingException("Address and target of mail is empty!");
}
} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
if (transport != null) try {
transport.close();
} catch (MessagingException ignore) {
}
}
}
}
It's working just perfect!!

Related

Send email through App without opening mail App in Android

so I searched a lot to send an email throught my app, but without the user having to log in in an email app and send it himself. I would like to just let him write it in an editText and then just press a button and send it to me. So that's what I did: 2 classes for the mail thing, my activity which calls it, add the 3 libraries and the internet permission. What did I do wrong?
Here is where I call the email process :
private View.OnClickListener btnMode1Listener = new
View.OnClickListener() {
#Override
public void onClick(View v) {
suggestionText = entre_suggestion.getText().toString();
Log.i("SendMailActivity", "Send Button Clicked.");
String fromEmail = "fromEmail#gmail.com";
String fromPassword = "frompassword";
String toEmails = "toEmail#gmail.com";
List toEmailList = Arrays.asList(toEmails
.split("\\s*,\\s*"));
Log.i("SendMailActivity", "To List: " + toEmailList);
String emailSubject = "Suggestion";
String emailBody = suggestionText;
new SendMailTask(suggestions.this).execute(fromEmail,
fromPassword, toEmailList, emailSubject, emailBody);
}
};
This is the first class "GMail":
public class GMail {
final String emailPort = "587";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";
String fromEmail;
String fromPassword;
List toEmailList;
String emailSubject;
String emailBody;
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public GMail() {
}
public GMail(String fromEmail, String fromPassword,
List toEmailList, String emailSubject, String emailBody) {
this.fromEmail = fromEmail;
this.fromPassword = fromPassword;
this.toEmailList = toEmailList;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", smtpAuth);
emailProperties.put("mail.smtp.starttls.enable", starttls);
Log.i("GMail", "Mail server properties set.");
}
public MimeMessage createEmailMessage() throws AddressException,
MessagingException, UnsupportedEncodingException {
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
for (Object toEmail : toEmailList) {
Log.i("GMail","toEmail: "+toEmail);
emailMessage.addRecipient(Message.RecipientType.TO,
new InternetAddress((String) toEmail));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");// for a html email
// emailMessage.setText(emailBody);// for a text email
Log.i("GMail", "Email Message created.");
return emailMessage;
}
public void sendEmail() throws AddressException, MessagingException {
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromEmail, fromPassword);
Log.i("GMail","allrecipients: "+emailMessage.getAllRecipients());
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
Log.i("GMail", "Email sent successfully.");
}
}
And this is the second class "SendMailtask":
public class SendMailTask extends AsyncTask {
private ProgressDialog statusDialog;
private Activity sendMailActivity;
public SendMailTask(Activity activity) {
sendMailActivity = activity;
}
protected void onPreExecute() {
statusDialog = new ProgressDialog(sendMailActivity);
statusDialog.setMessage("Getting ready...");
statusDialog.setIndeterminate(false);
statusDialog.setCancelable(false);
statusDialog.show();
}
#Override
protected Object doInBackground(Object... args) {
try {
Log.i("SendMailTask", "About to instantiate GMail...");
publishProgress("Processing input....");
GMail androidEmail = new GMail(args[0].toString(),
args[1].toString(), (List) args[2], args[3].toString(),
args[4].toString());
publishProgress("Preparing mail message....");
androidEmail.createEmailMessage();
publishProgress("Sending email....");
androidEmail.sendEmail();
publishProgress("Email Sent.");
Log.i("SendMailTask", "Mail Sent.");
} catch (Exception e) {
publishProgress(e.getMessage());
Log.e("SendMailTask", e.getMessage(), e);
}
return null;
}
#Override
public void onProgressUpdate(Object... values) {
statusDialog.setMessage(values[0].toString());
}
#Override
public void onPostExecute(Object result) {
statusDialog.dismiss();
}
}
And finally, the 3 librairies I added:
compile files('libs/activation.jar')
compile files('libs/additionnal.jar')
compile files('libs/mail.jar')
So yeah, I searched a lot and didn't find how to debug it. I tried a lot of different ways but it never sent the email. I just want to be clear that I don't want to open the mail app, I want the email to be sent without the user having to do something.
package com.auto.smartautomates.smartautomates.Helpers;
import com.crashlytics.android.Crashlytics;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
/**
* Created by sardar.khan on 6/8/2017.
*/
public class MailService {
// public static final String MAIL_SERVER = "localhost";
private String toList;
private String ccList;
private String bccList;
private String subject;
final private static String SMTP_SERVER = "smtp.gmail.com";
private String from;
private String txtBody;
private String htmlBody;
private String replyToList;
private boolean authenticationRequired = false;
public MailService(String from, String toList, String subject, String txtBody, String htmlBody) {
this.txtBody = txtBody;
this.htmlBody = htmlBody;
this.subject = subject;
this.from = from;
this.toList = toList;
this.ccList = null;
this.bccList = null;
this.replyToList = null;
this.authenticationRequired = true;
}
public void sendAuthenticated() throws AddressException, MessagingException {
authenticationRequired = true;
send();
}
/**
* Send an e-mail
*
* #throws MessagingException
* #throws AddressException
*/
public void send() throws AddressException, MessagingException {
Properties props = new Properties();
// set the host smtp address
props.put("mail.smtp.host", SMTP_SERVER);
props.put("mail.user", from);
props.put("mail.smtp.starttls.enable", "true"); // needed for gmail
props.put("mail.smtp.auth", "true"); // needed for gmail
props.put("mail.smtp.port", "587"); // gmail smtp port 587 default gmail
/*Authenticator auth = new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mobile#mydomain.com", "mypassword");
}
};*/
Session session;
if (authenticationRequired) {
Authenticator auth = new SMTPAuthenticator();
props.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(props, auth);
} else {
session = Session.getDefaultInstance(props, null);
}
// get the default session
session.setDebug(true);
// create message
Message msg = new javax.mail.internet.MimeMessage(session);
// set from and to address
try {
msg.setFrom(new InternetAddress(from, from));
msg.setReplyTo(new InternetAddress[]{new InternetAddress(from,from)});
} catch (Exception e) {
Crashlytics.logException(e);
msg.setFrom(new InternetAddress(from));
msg.setReplyTo(new InternetAddress[]{new InternetAddress(from)});
}
// set send date
msg.setSentDate(Calendar.getInstance().getTime());
// parse the recipients TO address
java.util.StringTokenizer st = new java.util.StringTokenizer(toList, ",");
int numberOfRecipients = st.countTokens();
javax.mail.internet.InternetAddress[] addressTo = new javax.mail.internet.InternetAddress[numberOfRecipients];
int i = 0;
while (st.hasMoreTokens()) {
addressTo[i++] = new javax.mail.internet.InternetAddress(st
.nextToken());
}
msg.setRecipients(javax.mail.Message.RecipientType.TO, addressTo);
// parse the replyTo addresses
if (replyToList != null && !"".equals(replyToList)) {
st = new java.util.StringTokenizer(replyToList, ",");
int numberOfReplyTos = st.countTokens();
javax.mail.internet.InternetAddress[] addressReplyTo = new javax.mail.internet.InternetAddress[numberOfReplyTos];
i = 0;
while (st.hasMoreTokens()) {
addressReplyTo[i++] = new javax.mail.internet.InternetAddress(
st.nextToken());
}
msg.setReplyTo(addressReplyTo);
}
// parse the recipients CC address
if (ccList != null && !"".equals(ccList)) {
st = new java.util.StringTokenizer(ccList, ",");
int numberOfCCRecipients = st.countTokens();
javax.mail.internet.InternetAddress[] addressCC = new javax.mail.internet.InternetAddress[numberOfCCRecipients];
i = 0;
while (st.hasMoreTokens()) {
addressCC[i++] = new javax.mail.internet.InternetAddress(st
.nextToken());
}
msg.setRecipients(javax.mail.Message.RecipientType.CC, addressCC);
}
// parse the recipients BCC address
if (bccList != null && !"".equals(bccList)) {
st = new java.util.StringTokenizer(bccList, ",");
int numberOfBCCRecipients = st.countTokens();
javax.mail.internet.InternetAddress[] addressBCC = new javax.mail.internet.InternetAddress[numberOfBCCRecipients];
i = 0;
while (st.hasMoreTokens()) {
addressBCC[i++] = new javax.mail.internet.InternetAddress(st
.nextToken());
}
msg.setRecipients(javax.mail.Message.RecipientType.BCC, addressBCC);
}
// set header
msg.addHeader("X-Mailer", "MyAppMailer");
msg.addHeader("Precedence", "bulk");
// setting the subject and content type
msg.setSubject(subject);
Multipart mp = new MimeMultipart("related");
// set body message
MimeBodyPart bodyMsg = new MimeBodyPart();
bodyMsg.setText(txtBody, "iso-8859-1");
bodyMsg.setContent(htmlBody, "text/html");
mp.addBodyPart(bodyMsg);
msg.setContent(mp);
// send it
try {
javax.mail.Transport.send(msg);
} catch (Exception e) {
Crashlytics.logException(e);
e.printStackTrace();
}
}
/**
* SimpleAuthenticator is used to do simple authentication when the SMTP
* server requires it.
*/
private static class SMTPAuthenticator extends javax.mail.Authenticator {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "someEmail#gmail.com";
String password ="yourPassword";
return new PasswordAuthentication(username, password);
}
}
public String getToList() {
return toList;
}
public void setToList(String toList) {
this.toList = toList;
}
public String getCcList() {
return ccList;
}
public void setCcList(String ccList) {
this.ccList = ccList;
}
public String getBccList() {
return bccList;
}
public void setBccList(String bccList) {
this.bccList = bccList;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setFrom(String from) {
this.from = from;
}
public void setTxtBody(String body) {
this.txtBody = body;
}
public void setHtmlBody(String body) {
this.htmlBody = body;
}
public String getReplyToList() {
return replyToList;
}
public void setReplyToList(String replyToList) {
this.replyToList = replyToList;
}
public boolean isAuthenticationRequired() {
return authenticationRequired;
}
public void setAuthenticationRequired(boolean authenticationRequired) {
this.authenticationRequired = authenticationRequired;
}
}
In your account settings, allow smtp, and allow unsafe apps

Display HTML table data from servlet to email but I am getting the plain text in the email

I am using following code. But in the mail, I am getting the palin html tags only not output in table format. Please help me to get the output as table format in the mail
StringBuilder content = new StringBuilder();
content.append("<HTML>")
.append("<HEAD>")
.append("<TITLE>Welcome</TITLE>")
.append("</HEAD>")
// Start on the body
.append("<BODY>")
.append("<CENTER>")
.append("<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 WIDTH=70%>")
.append("<TR>")
.append("<TH style=\"padding:5px\">Subject</TH>")
.append("<TH style=\"padding:5px\">Grade</TH>")
.append("</TR>")
.append("<TR>")
.append("<TD>Mathmatics</TD>")
.append("<TD>A</TD>")
.append("</TR>")
.append("<TR>")
.append("<TD>SCEINECE</TD>")
.append("<TD>B</TD>")
.append("</TR>")
.append("</TABLE>")
.append("</CENTER>")
.append("</BODY></HTML>");
String resultMessage = "";
try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject, content.toString());
}
i have used javax mail. this will work
public class Main {
public static void main(String[] arg) {
StringBuilder MessageContent = new StringBuilder();
MessageContent.append("<HTML>")
.append("<HEAD>")
.append("<TITLE>Welcome</TITLE>")
.append("</HEAD>")
// Start on the body
.append("<BODY>")
.append("<CENTER>")
.append("<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 WIDTH=70%>")
.append("<TR>")
.append("<TH style=\"padding:5px\">Subject</TH>")
.append("<TH style=\"padding:5px\">Grade</TH>")
.append("</TR>")
.append("<TR>")
.append("<TD>Mathmatics</TD>")
.append("<TD>A</TD>")
.append("</TR>")
.append("<TR>")
.append("<TD>SCEINECE</TD>")
.append("<TD>B</TD>")
.append("</TR>")
.append("</TABLE>")
.append("</CENTER>")
.append("</BODY></HTML>");
MailParam mp = new MailParam();
mp.setUsername("....");
.....
Properties props = new Properties();
props.put("mail.smtp.auth", mailParam.getAuth());
props.put("mail.smtp.starttls.enable", mailParam.getStartls());
props.put("mail.smtp.host", mailParam.getHost());
props.put("mail.smtp.port", mailParam.getPort());
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
try {
messageBodyPart.setContent(MessageContent, "text/html; charset=utf-8");
//messageBodyPart.setText(MessageContent);
multipart.addBodyPart(messageBodyPart);
} catch (MessagingException e) {
e.printStackTrace();
}
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailParam.getUsername(), mailParam.getPwd());
}
});
// Sender's email ID needs to be mentioned
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
message.addHeader("Content-type", "text/HTML; charset=UTF-8");
message.addHeader("Content-Transfer-Encoding", "quoted-printable");
// Set From: header field of the header.
message.setFrom(new InternetAddress("your_mail#yourdomain");
//message.setRecipients(Message.RecipientType.TO,recipientAddress);
message.setRecipients(Message.RecipientType.TO, "npsantost#libero.it");
// Set Subject: header field
message.setSubject("my subject");
// Send the actual HTML message, as big as you like
//message.setContent("<h1>This is actual message</h1>", "text/html");
message.setContent(multipart);
// Send message
Transport.send(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
MailParam class
public class MailParam {
private String username;
String pwd;
String auth;
String startls;
String host;
String port;
String from;
String replyto;
String logopath;
public String getAuth() {
return auth;
}
public String getHost() {
return host;
}
public String getPort() {
return port;
}
public String getPwd() {
return pwd;
}
public String getStartls() {
return startls;
}
public String getUsername() {
return username;
}
public String getFrom() {
return from;
}
public String getReplyto() {
return replyto;
}
public String getLogopath() {
return logopath;
}
public void setAuth(String val) {
auth = val;
}
public void setHost(String val) {
host = val;
}
public void setPort(String val) {
port = val;
}
public void setPwd(String val) {
pwd = val;
}
public void setStartls(String val) {
startls = val;
}
public void setUsername(String val) {
username = val;
}
public void setFrom(String val) {
from = val;
}
public void setReplyto(String val) {
replyto = val;
}
public void setLogoPath(String val) {
logopath = val;
}
}
Here is my Utility class code:
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
// sends the e-mail
Transport.send(msg);
}
}
add this block in your Class EmailUtility
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
try {
messageBodyPart.setContent(message, "text/html; charset=utf-8");
//messageBodyPart.setText(MessageContent);
multipart.addBodyPart(messageBodyPart);
} catch (MessagingException e) {
e.printStackTrace();
}
then replace
msg.setText(message);
with
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setContent(multipart);

Sending mail from service using smtp

My app runs a service which sends and email, this must be transparent for the user, so I use javax.mail.
These are the classes I implement:
JSSEProvider.java
public final class JSSEProvider extends Provider {
private static final long serialVersionUID = 1L;
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
#Override
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
MailSender.java
public class MailSender extends javax.mail.Authenticator {
private final String mailhost = "smtp.gmail.com";
private final String user;
private final String password;
private final Session session;
static {
Security.addProvider(new JSSEProvider());
}
public MailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactor.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
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);
}
public class ByteArrayDataSource implements DataSource {
private final byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
#Override
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
#Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
#Override
public String getName() {
return "ByteArrayDataSource";
}
#Override
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
And finally, this is how I send the email from service:
private void sendEmail(String email) {
String from = "mymail#gmail.com";
String pass = "mypass";
String to = email;
String subject = getString(R.string.email_subject);
String body = text_i_want_to_send;
MailSender mail = new MailSender(from, pass);
try {
mail.sendMail(subject, body, from, to);
Log.d("EMAIL", "Email sent!");
} catch (Exception e) {
Log.d("EMAIL", "Error: " + e.getMessage());
}
}
Now, the problem is that, when it should send the email, I can see in the LogCat the exception refered to the catch statement, but it does not give any details, it just says:
EMAIL Error: null
Have to say that I have goten the JSSEProvider and the MailSender clases from the diferent tutorials around the net about using javax.mail to send mails using smtp.
So, I have no clue about what I'm doing wrong
EDIT --
I have chaught the exception, and it was related to doing network operation on the main thread. So I'm using now an AsyncTask and this part is solved.
But now, I have another exception, related to authentication this time. I have received an email in my email account telling that some has tried to access to my account (me) and that gmail has blocked it. So, how can I solve this authentication issue?
Can you add a catch for a NullPointerException?
(and add throw e).
I guess you have a null pointer somewhere and like this you can have more data.
Therefor it's a bad habit to catch "Exception" as everything will be caught.

ERROR Could not instantiate class

I work with log4j.properties through WSO2 products. I needed implement a appender to work with SMTPAppender and send emails notifications using gmail smtp server. So, when I config log4j and start ESB WSO2 Server, the manage console print: log4j:ERROR Could not instantiate class [com.notification.GmailSMTPAppender].
My implementation was:
package com.notification;
public class GmailSMTPAppender extends SMTPAppender {
protected Session session;
public GmailSMTPAppender() {
super();
}
/**
* Create mail session.
*
* #return mail session, may not be null.
*/
protected Session createSession() {
Properties props = new Properties();
props.put("mail.smtps.host", getSMTPHost());
props.put("mail.smtps.auth", "true");
Authenticator auth = null;
if (getSMTPPassword() != null && getSMTPUsername() != null) {
auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getSMTPUsername(),
getSMTPPassword());
}
};
}
session = Session.getInstance(props, auth);
if (getSMTPProtocol() != null) {
session.setProtocolForAddress("rfc822", getSMTPProtocol());
}
if (getSMTPDebug()) {
session.setDebug(getSMTPDebug());
}
return session;
}
/**
* Send the contents of the cyclic buffer as an e-mail message.
*/
protected void sendBuffer() {
try {
MimeBodyPart part = new MimeBodyPart();
StringBuffer sbuf = new StringBuffer();
String t = layout.getHeader();
if (t != null)
sbuf.append(t);
int len = cb.length();
for (int i = 0; i < len; i++) {
LoggingEvent event = cb.get();
sbuf.append(layout.format(event));
if (layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
for (int j = 0; j < s.length; j++) {
sbuf.append(s[j]);
sbuf.append(Layout.LINE_SEP);
}
}
}
}
t = layout.getFooter();
if (t != null)
sbuf.append(t);
part.setContent(sbuf.toString(), layout.getContentType());
Multipart mp = new MimeMultipart();
mp.addBodyPart(part);
msg.setContent(mp);
msg.setSentDate(new Date());
send(msg);
} catch (Exception e) {
LogLog.error("Error occured while sending e-mail notification.", e);
}
}
/**
* Pulled email send stuff i.e. Transport.send()/Transport.sendMessage(). So
* that on required this logic can be enhanced.
*
* #param msg
* Email Message
* #throws MessagingException
*/
protected void send(Message msg) throws MessagingException {
SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
try {
t.connect(getSMTPHost(), getSMTPUsername(), getSMTPPassword());
t.sendMessage(msg, msg.getAllRecipients());
} finally {
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
}
How I can instantiate of this appender on my log4j.properties configuration ??
Do you need to programatically add the Appender?
Check the following post

problem in sending mail in Java

two exception comes in my program.......
cannot connect to the localhost ,port 25
connection refused
code of mail.java is ---
package jMail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Mail {
private String to;
private String from;
private String message;
private String subject;
private String smtpServ;
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSmtpServ() {
return smtpServ;
}
public void setSmtpServ(String smtpServ) {
this.smtpServ = smtpServ;
}
public Exception sendMail(){
try
{
Properties props = System.getProperties();
// -- Attaching to default Session, or we could start a new one --
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host","localhost");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
// -- We could include CC recipients too --
// if (cc != null)
// msg.setRecipients(Message.RecipientType.CC
// ,InternetAddress.parse(cc, false));
// -- Set the subject and body text --
msg.setSubject(subject);
msg.setText(message);
// -- Set some other header information --
msg.setHeader("MyMail", "Java Mail Test");
msg.setSentDate(new Date());
// -- Send the message --
Transport.send(msg);
System.out.println("Message sent to"+to+" OK.");
return null;
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println("Exception "+ex);
return ex;
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
#Override
public PasswordAuthentication getPasswordAuthentication() {
String username = "Java.Mail.CA#gmail.com";
String password = "javamail";
return new PasswordAuthentication(username, password);
}
}
}
so please tell me what to do & why these exception arises & how can i can mail using the java & localhost as host.
....................... thanks in advance.
Just follow this code; it is really useful to send email into java desktop and it works.
import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;
import javax.mail.internet.*;
public class Main
{
public static void main(String[] args)
{
final String username = "your#gmail.com";
final String password = "password";
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
try
{
String body = "Dear Renish Khunt Welcome";
String htmlBody = "<strong>This is an HTML Message</strong>";
String textBody = "This is a Text Message.";
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("receiver#gmail.com"));
message.setSubject("Testing Subject");
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);
message.setText(htmlBody);
message.setContent(textBody, "text/html");
Transport.send(message);
System.out.println("Done");
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}
Here is the code snippet to send email.
try {
String host = "yourHostName";
String from = "test#test.com";
String to[] = {"test123#test123.com"};
String subject = "Test";
String message = "Test";
Properties prop = System.getProperties();
prop.put("mail.smtp.host", host);
Session sess1 = Session.getInstance(prop, null);
MimeMessage msg = new MimeMessage(sess1);
msg.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
msg.setRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject);
//Fill the message
msg.setText(message);
Transport.send(msg);
} catch (MessagingException me) {
me.printStackTrace();
}
What exceptions are you getting while sending emails? Are you sure your SMTP server is listening at default port 25? Are you able to manually send the email via Telnet? Also, turn off any firewall while testing this just to be sure.

Categories