I am making a program that sends information to my email and I am taking reference from the given java code. But I am getting authentication failed error. Any one have an idea to send SMTP mail without allowing less secure from gmail and yahoo? Please help me out.
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
import java.io.*;
public class Emailer
{
private static final String SMTP_HOST_NAME = "smtp.live.com";
private static final String SMTP_AUTH_USER = "mokee#live.com";
private static final String SMTP_AUTH_PWD = "spidermonkey";
private static final String emailMsgTxt = "Online Order Confirmation Message. Also include the Tracking Number.";
private static final String emailSubjectTxt = "HELEEEELEQWEWEQ!!!";
private static final String emailFromAddress = "mokee#live.com";
// Add List of Email address to who email needs to be sent to
private static final String[] emailList = {"mokee#live.com"};
public static void main(String emailBody) throws Exception
{
Emailer smtpMailSender = new Emailer();
smtpMailSender.postMail( emailList, emailSubjectTxt, emailBody, emailFromAddress);
System.out.println("Sucessfully Sent mail to All Users");
}
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException {
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private class SMTPAuthenticator extends javax.mail.Authenticator
{
private Session createSmtpSession() {
final Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.live.com");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "" + 587);
props.setProperty("mail.smtp.starttls.enable", "true");
// props.setProperty("mail.debug", "true");
return Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mokee#live.com", "spidermonkey");
}
});
}
}
}
However, whenever I run this I get the following error message:
Exception in thread "main" javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at javax.mail.Service.connect(Service.java:329)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at client.Emailer.postMail(Emailer.java:102)
at client.Emailer.main(Emailer.java:67)
at client.RemoteFileClient.main(RemoteFileClient.java:28)
You have created
private Session createSmtpSession()
But you did not use it.
Here is your solution.
public void postMail( String recipients[ ], String subject, String message , String from)
throws MessagingException {
Session session = null;
Properties props = new Properties();
props.setProperty("mail.smtp.host", SMTP_HOST_NAME );
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "" + 587);
props.setProperty("mail.smtp.starttls.enable", "true");
// props.setProperty("mail.debug", "true");
session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SMTP_AUTH_USER,SMTP_AUTH_PWD);
}
});
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
Related
I have written code that sends email using outlook.office365.com. When I am running the program getting the following error.
javax.mail.MessagingException: Could not connect to SMTP host: outlook.office365.com, port: 587;
nested exception is:
java.net.SocketException: Permission denied: connect
private static final String SERVIDOR_SMTP = "outlook.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();
}
I think, you don't have permission for access your email. For example while i try in my gmail account, if i don't open the setting that show at below, i get a authorization failed but if i open the setting, i can send e-mail with your code.
Please check your e-mail permission and settings.
settings picture
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
I dont know y i am unable to send mail from tab. It gives exception saying cud not communicate, network unreachable.
Gmailsender.java
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
private Multipart _multipart = new MimeMultipart();
static {
Security.addProvider(new JSSEProvider());
}
public GMailSender(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.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
props.setProperty("mail.smtp.ssl.enable", "true");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body,
String sender, String recipients) throws Exception {
try {
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);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(_multipart);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(recipients));
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public class ByteArrayDataSource implements DataSource {
private 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;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
I called this from activity as below.
GMailSender gMailSender=new GMailSender("user#abc.com","passwd");
gMailSender.sendMail(subject,message,"user#abc.com","to#abc.com");
Any suggestion wil be very helpful.
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);
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.