I want to read HTML file and want to send HTML formatted email.
public class SendEmailer {
public void sendHtmlEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// sets SMTP server properties
Properties properties = new Properties();
properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
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");
properties.put("mail.store.protocol","pop3");
properties.put("mail.transport.protocol","smtp");
// 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());
// set plain text message
msg.setContent(message, "text/html");
// sends the e-mail
Transport.send(msg);
}
//Code to read HTML document.
public void readHTML(String strfilename,String content){
// content="";
String str="";
try{
FileReader fr=new FileReader(strfilename);
BufferedReader br=new BufferedReader(fr);
while((str=br.readLine())!=null){
System.out.println(str.toString());
content+=str;
}
br.close();
}catch(IOException ie){
ie.printStackTrace();
}
}
public static void main(String[] args) {
// SMTP server information
String host = "myhost.com";
String port = "465";
String mailFrom = "abc#myhost.com";
String password = "abcd123";
// outgoing message information
String mailTo = "abc#gmail.com";
String subject = "Test mail";
// message contains HTML markups
String message = "<i>Greetings!Sending HTML mail.</i><br>";
message += "<font color=red>MyName</font>";
SendEmailer mailer = new SendEmailer ();
String filename="E:/filepath/filename.html";
try {
mailer.readHTML(filename);
mailer.sendHtmlEmail(host, port, mailFrom, password, mailTo,
subject, message);
System.out.println("Email sent successfully.");
} catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
}
I am able to send email successfully. But now I want to send the full body part of the html file. I wrote a method readHTML(), but its not reading the content of that file neither it sends the same. It sends only what I've stored in message variable. Where did I make mistake?
Related
I have an web application in which i am sending mail to user. Following is my code.
String host = "smtp.gmail.com";
String pwd = "123";
String from = "sender#gmail.com";
String to = "receiver#gmail.com";
String subject = "Test";
String messageText = "This is demo mail";
int port = 587;
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] add = {new InternetAddress(to)};
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setRecipients(Message.RecipientType.TO, add);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText); //Actual msg
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, from, pwd);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
This code is executed on local but fails on server domain. I have search a lot but that solution didn't work for me.
I tried a lot like replacing transport.connect(host, from, pwd); with transport.connect(host, 587, from, pwd); or 465and also String host="smtp.gmail.com"; with static domain IP. but still not working.
can anyone figure out what i am missing..?
Here is working example.
If this didn't work then there must be a problem with your server..
public static void sendEmail(String host, String port, final String userName, final String password, String recipient, String subject, String message, File attachFile) throws AddressException, MessagingException, UnsupportedEncodingException {
// sets SMTP server properties
try {
logger.info("Sending Email to : " + recipient + " Subject :" + subject);
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");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
#Override
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, userName));
if (recipient.contains(";")) {
String[] recipientList = recipient.split(";");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String obj: recipientList) {
recipientAddress[counter] = new InternetAddress(obj.trim());
counter++;
}
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
} else {
InternetAddress[] recipientAddress = {
new InternetAddress(recipient)
};
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
}
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFile != null) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(attachFile);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
} catch (Exception e) {
logger.error("ERROR In Sending Email :" + e, e);
}
}
I'm need to send an email after persist an object on my JAVA project, I'm using this code
public static void sendMail(String protocol, String host, String port, final String userName, final String password,
String subject, byte[] content, String para, String cc, String co) {
Properties props = getServerProperties(protocol, host, port);
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
final Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(userName));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(para));
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(co));
message.setSubject(subject);
message.setText(content.toString());
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private static Properties getServerProperties(String protocol, String host, String port) {
Properties properties = new Properties();
properties.put(String.format("mail.%s.host", protocol), host);
properties.put(String.format("mail.%s.port", protocol), port);
properties.setProperty(String.format("mail.%s.socketFactory.class", protocol), "javax.net.ssl.SSLSocketFactory");
properties.setProperty(String.format("mail.%s.socketFactory.fallback", protocol), "false");
properties.setProperty(String.format("mail.%s.socketFactory.port", protocol), String.valueOf(port));
return properties;
}
but when I call Transport.send(message); returns me an error message
Can't make API call mail.Send in a thread that is neither the original request thread nor a thread created by ThreadManager
What i'm doing wrong on mailer?
I'm trying to create a program using the JavaMail API, however, I keep getting the following error message.
javax.mail.NoSuchProviderException: invalid provider
at javax.mail.Session.getTransport(Session.java:738)
at javax.mail.Session.getTransport(Session.java:682)
at javax.mail.Session.getTransport(Session.java:662)
at EmailAutoResponder2.main(EmailAutoResponder2.java:56)
I was not able to solve it by reading online, as all of their solutions still gave me the same message.
Here is the Java code:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailAutoResponder2 {
public static void main(String[] args) {
String to = "username#videotron.ca";
String from = "username#videotron.ca";
Properties properties = System.getProperties();
properties.setProperty("mail.store.protocol", "imaps");
Session session1 = Session.getInstance(properties);
//If email received by specific user, send particular response.
Properties props = new Properties();
props.put("mail.imap.auth", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.host", "imap.videotron.ca");
props.put("mail.imap.port", "143");
Session session2 = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username#videotron.ca", "password");
}
});
try {
Store store = session2.getStore("imap");
store.connect("imap.videotron.ca", "username#videotron.ca", "password");
Folder fldr = store.getFolder("Inbox");
fldr.open(Folder.READ_ONLY);
Message msgs[] = fldr.getMessages();
for(int i = 0; i < msgs.length; i++){
System.out.println(InternetAddress.toString(msgs[i].getFrom()));
if (InternetAddress.toString(msgs[i].getFrom()).startsWith("Name")){
MimeMessage message = new MimeMessage(session1);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject");
message.setText("Message");
String protocol = "imap";
props.put("mail." + protocol + ".auth", "true");
Transport t = session2.getTransport("imap");
try {
t.connect("username#videotron.ca", "password");
t.sendMessage(message, message.getAllRecipients());
}
finally {
t.close();
}
}
}
}
catch(MessagingException mex){
mex.printStackTrace();
}
catch(Exception exc) {
}
}
}
Thank you!
You're connecting to localhost to send the message. Do you have a mail server running on your local machine? Probably not. You need to set the mail.smtp.host property. You may also need to supply a username and password for your mail server; see the JavaMail FAQ.
The following code may solve your problem
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
I'm trying to send an email with an attachment. The whole thing works fine, except for the part that the attachment sent sends the attached file with no extension.
For example, sending File.rar will receive file
This is how I'm doing it:
public class EmailSender {
public static void main(String[] args) {
String TO = "Receiver#yahoo.com";
String host = "smtp.gmail.com";
String port = "465";
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties mailConfig = new Properties();
mailConfig.put("mail.smtp.host", host);
mailConfig.put("mail.smtp.socketFactory.port", port);
mailConfig.put("mail.smtp.socketFactory.class", SSL_FACTORY);
mailConfig.put("mail.smtp.auth", "true");
mailConfig.put("mail.smtp.port", port);
Session session = Session.getDefaultInstance(mailConfig,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("Username", "Password");
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#gmail.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
message.setSubject("Email with Attachment SUBJECT");
BodyPart messageBodyTxt = new MimeBodyPart();
messageBodyTxt.setText("Email with Attachment BODY");
MimeBodyPart messageBodyAttachment = new MimeBodyPart();
String filePath = "D:\\Unlocker1.9.2.rar";
DataSource source = new FileDataSource(filePath);
messageBodyAttachment.setDataHandler(new DataHandler(source));
messageBodyAttachment.setFileName("Unlocker1.9.2" + ".rar");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyTxt);
multipart.addBodyPart(messageBodyAttachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Email sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Using the advice from the comment, the proper method would be setDisposition and you would set it for the MimeBodyPart in question. Therefore, with the code above, one would do:
messageBodyAttachment.setDisposition(javax.mail.Part.ATTACHMENT);
i working with registration page in this i need to send to a verification link to mail,while executing a got error and saying that java.net.ConnectException: Connection refused: connect
so please help me thanku
register.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>REGISTRATION</title>
</head>
<body>
<%!
DBCreation creation;
Connection connection;
%>
<%
String uid=request.getParameter("userid");
String pwd=request.getParameter("pwd");
String fName=request.getParameter("fname");
String lName=request.getParameter("lname");
String email=request.getParameter("email");
String location=request.getParameter("location");
String encpwd=encryptPwd(pwd);
System.out.println(encpwd);
connection=DBCreation.getConnection();
String result;
// Recipient's email ID needs to be mentioned.
String toEmail = email;
// Sender's email ID needs to be mentioned
String fromEmail = "nbarath2008#gmail.com";
// Assuming you are sending email from localhost
//String host = "localhost";
// Get system properties object
Properties properties = System.getProperties();
// Setup mail server
// properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session mailSession = Session.getDefaultInstance(properties);
Transport transport = new SMTPTransport(mailSession,new URLName("localhost"));
transport.connect("localhost",25,null,null);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);
// Set From: header field of the header.
message.setFrom(new InternetAddress(fromEmail));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,""+email);
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Send the actual HTML message, as big as you like
message.setContent("<h1>This is actual message</h1>",
"text/html" );
// Send message
Transport.send(message);
result = "Sent message successfully....";
PreparedStatement statement=connection.prepareStatement("insert into userregistration values(?,?,?,?,?,?,?)");
statement.setString(1,uid);
statement.setString(2,encpwd);
statement.setString(3,fName);
statement.setString(4, lName);
statement.setString(5, location);
statement.setString(6, fromEmail);
statement.setString(7, toEmail);
int i=statement.executeUpdate();
if(i>0)
{
// Send message
Transport.send(message);
result = "Sent message successfully....";
RequestDispatcher rd=request.getRequestDispatcher("regsuccess.jsp");
rd.forward(request, response);
}
}catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
</html>
This is the working code. Please ask you have any doubts!
import java.util.;
import javax.mail.;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "gmail-user-name"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "******"; // Enter your GMail password
private static String RECIPIENT = "RECIPIENT EMAIL address";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}