I am trying to send an html file containing some hindi content using javamail. Here is a screenshot of the file content:
The code I am using to send the file is as:
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.*;
/**
* Simple Class to send an email using JavaMail API (javax.mail) and Gmail SMTP server
* #author Dunith Dhanushka, dunithd#gmail.com
* #version 1.0
*/
public class GmailSender {
private static String HOST = "smtp.gmail.com";
private static String USER = "myemail#gmail.com";
private static String PASSWORD = "mypassword";
private static String PORT = "465";
private static String FROM = "recipientemail#gmail.com";
private static String TO = "toemail#gmail.com";
private static String STARTTLS = "true";
private static String AUTH = "true";
private static String DEBUG = "true";
private static String SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory";
private static String SUBJECT = "Testing JavaMail API";
private static String TEXT = "Message with attachment from my java application. Just ignore it";
public static synchronized void send() {
//Use Properties object to set environment properties
Properties props = new Properties();
props.put("mail.smtp.host", HOST);
props.put("mail.smtp.port", PORT);
props.put("mail.smtp.user", USER);
props.put("mail.smtp.auth", AUTH);
props.put("mail.smtp.starttls.enable", STARTTLS);
props.put("mail.smtp.debug", DEBUG);
props.put("mail.smtp.socketFactory.port", PORT);
props.put("mail.smtp.socketFactory.class", SOCKET_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
try {
//Obtain the default mail session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
//Construct the mail message
MimeMessage message = new MimeMessage(session);
message.setText(TEXT);
message.setSubject(SUBJECT);
message.setFrom(new InternetAddress(FROM));
message.addRecipient(RecipientType.TO, new InternetAddress(TO));
//add attachments
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "filenamewithpath";
String fileName = "attachmentName.html";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart,"UTF-8");
message.saveChanges();
//Use Transport to deliver the message
Transport transport = session.getTransport("smtp");
transport.connect(HOST, USER, PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
public static void main(String[] args) {
GmailSender.send();
System.out.println("Mail sent successfully!");
}
And very interestingly what is received is this:
When I do the same from my web browser, the mail is received correctly. Here is the details of the attached part(we get it by clicking the show original option in gmail inbox):
Content-Type: text/html; charset=UTF-16BE; name="filename.html"
Content-Disposition: attachment; filename="filaname.html"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_hl0znk4d0
So the encoding is "UTF-16BE". I have tried to change the encoding to "UTF-16BE" from "UTF-8" but no difference. Can anyone help me with this?
try this code. Its works for my language like मराठी, हिन्दी , English etc.
message.setContent(multipart, "text/html; charset=utf-8");
Read this and this and simplify your program.
You can't set an encoding for a multipart. Change
message.setContent(multipart,"UTF-8");
to
message.setContent(multipart);
Since your multipart only contains a single part, you don't really need the multipart at all, but we'll ignore that for now.
The file that you're attaching will be assumed to be using the default charset for the locale the server is running in. That may not be "utf-8". In fact, it may be "utf-16be". If the file really is using utf-8, try setting the System property "mail.mime.charset" to "utf-8".
Related
I am getting the syntax for the below line while trying to send the mail through SMTP .I tried in google but didnt get any relevant answer.
property.setProperty("mail.smtp.host",host);
CODE:
public class SendMail {
//Recipient Mail id
String to = "Receiver Mail ID";
//Sender Mail Id
String from = "Sender Mail ID";
//Sending email from the localhost
String host = "localhost";
//Get System Properties
Properties property = System.getProperties();
//Setup the mail server
property.setProperty("mail.smtp.host",host);
property.setProperty("mail.smtp.port" , "465");
//property.put("mail.smtp.auth", "true");
//Get the default session object
Session session = Session.getDefaultInstance(property);
try
{
//Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
//Set From: header field of the header
message.setFrom(new InternetAddress(from));
//Set To : header field of the header
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//Set Subject : header field
message.setSubject("Automation Testing Report");
//Create the Message part
BodyPart messageBodypart = new MimeBodyPart();
//Enter the message in the Mail Body
messageBodypart.setText("***********Find the below for the Report****************");
//Create a Multipart Message
Multipart multipart = new MimeMultipart();
//Set Text message part
multipart.addBodyPart(messageBodypart);
//Part two is attachment
/*create the Message part*/
messageBodypart = new MimeBodyPart();
String filename = "E:\\Project\\jar\\Selenium Scripts\\Hybrid_Driven\\test-output\\emailable-report.html";
DataSource source = new FileDataSource(filename);
messageBodypart.setDataHandler(new DataHandler(source));
messageBodypart.setFileName(filename);
//set the text message part
multipart.addBodyPart(messageBodypart);
//Send the complete message part
message.setContent(multipart);
//Send message
Transport.send(message);
System.out.println("Mail has sent successfully");
}
catch(MessagingException mex)
{
mex.printStackTrace();
}
}
}
Please help me to resolve this issue.
You cannot put java code directly into a class. It needs to be within methods. The following is happily accepted by the compiler:
public class SendMail {
...
//Get System Properties
java.util.Properties property = System.getProperties();
void doSomething()
{
property.setProperty("mail.smtp.host", host);
property.setProperty("mail.smtp.port", "465");
...
}
}
i want to send a file in attachment using java.
I have two classes, one where the file location is specified and the second class is used as utility class to send the email
So when i execute the first class it does not send the email.
First class:
public class SendFile {
private static String[] args;
public static void sendEmail(File filetosend) throws IOException, Exception{
//public static void main(String[] args) throws IOException {
final String username = "email0#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
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("email0#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("email0#gmail.com"));
message.setSubject("Attach file Test from Netbeans");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
//String filetosend = ("c:\\file.txt");
DataSource source = new FileDataSource(filetosend);
System.out.println("The filetosend is ="+filetosend);
messageBodyPart.setDataHandler(new DataHandler(source));
System.out.println("The source is ="+source);
messageBodyPart.attachFile(filetosend);
System.out.println("The file name is ="+messageBodyPart.getFileName());
multipart.addBodyPart(messageBodyPart);
System.out.println("The message body part is ="+messageBodyPart);
message.setContent(multipart);
System.out.println("The message multi part is ="+multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("The message is ="+message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
And the second class:
import java.io.File;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws Exception {
}
File file;
public void Test() throws IOException, Exception{
System.out.println("Sending the file...");
File filetosend = new File("c:\\file.txt");
SendFile.sendEmail(filetosend);
}
}
There is no error but the file is not sent.
Any help please, thank you
Your code is wrong. If you copied it from somewhere, the original is wrong too, or you copied it wrong. This is what you want:
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("email0#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("email0#gmail.com"));
message.setSubject("Attach file Test from Netbeans");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("PFA");
attachmentBodyPart = new MimeBodyPart();
System.out.println("The filetosend is ="+filetosend);
System.out.println("The source is ="+source);
attachmentBodyPart.attachFile(filetosend);
System.out.println("The file name is ="+attachmentBodyPart.getFileName());
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentBodyPart);
message.setContent(multipart);
System.out.println("The message multi part is ="+multipart);
System.out.println("Sending");
Transport.send(message);
Your code looks fine. In fact, I use almost the exact same code to send messages with attachments. You should probably look at whether or not you need to add authentication to the Transport and connect using the host, port, auth id, and auth pass. Also, check for any firewalls blocking messages with attachments (incredibly common issue).
If you look at this post Stack Overflow post on sending multiple attachments
You will see that nearly the same thing is done, and it gives an example on how to send the message with authentication.
I would like to send email without authentication using java.
Can someone help me?
With authentication, I do it as follows:
public void sendEmail() throws EmailException{
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.addTo("XXX#gmail.com", "XXXX");
email.setFrom("XXXX#gmail.com","XXXXX");
email.setSubject("testando . . .");
email.setMsg("testando 1");
email.setSSL(true);
email.setAuthentication("xxxxxx#gmail.com", "XXXXX");
email.send();
}
I forgot to say that i do not have a provider. i need an provider finally, i have emailFrom Subject and Message, and need send this email how?
If it is only for testing purposes, you may try Papercut. While it’s running, Papercut automatically picks up e-mail sent to the standard SMTP port (25) on any IP address. You just send mail from your application and switch to Papercut to review it.
Papercut # github:
https://github.com/ChangemakerStudios/Papercut/releases
import java.util.Date;
import java.util.Properties;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", "127.0.0.1");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("admin#test.com"));
message.setRecipient(RecipientType.TO, new InternetAddress("a#b.com"));
message.setSubject("Notification");
message.setText("Successful!", "UTF-8"); // as "text/plain"
message.setSentDate(new Date());
Transport.send(message);
}
}
import java.util.*;
import javax.mail.*;
public class SimpleEmail {
public static void main(String[] args) {
System.out.println("SimpleEmail Start");
String smtpHostServer = "smtp.gmail.com";
String toEmail = "XXXX#gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(props);
try {
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("n91eply#gmail.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("n91eply#gmail.com", false));
msg.setSubject("SimpleEmail Testing Subject", "UTF-8");
msg.setText("SimpleEmail Testing Body", "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Try this example:
// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Via: tutorialspoint
Trying to get Play! Framework to send an email with an attachment. Code below works fine if I don't add the attachment to the message. I've tried both with Play's Mailer class and with the Apache Commons classes (as below), but in both cases, the page just sits there with a spinner (Chrome) and no email is received.
EmailAttachment attachment = new EmailAttachment();
attachment.setURL(new URL(base + "public/images/triangles.png"));
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("test");
attachment.setName("test");
emailaddress = "test#test.com";
MultiPartEmail email = new MultiPartEmail();
email.setDebug(true);
email.addTo(emailaddress);
email.setFrom("Testing <test#test.com>");
email.setSubject("Testing email");
try
{
email.attach(attachment);
}
catch (EmailException ex)
{
System.out.println(ex.getMessage());
}
email.setMsg("test email");
email.send();
Im guessing you've already had a look at the Examples for Apache Commons and Sending e-mail - Play! Framework 1.1?
IMO I'd suggest using a well known library with loads of documentation and examples like JavaMail and their api.
Here are a few tutorials that will get you started immediately:
JavaMail quick start
Java Mail SMTPClient Example
Sending mail with attachment with javamail
An example of using the JavaMail to send a Email with attachment via gmail is:
import java.util.Properties;
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 SendMailTLS {
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Define message
MimeMessage message =
new MimeMessage(session);
message.setFrom(
new InternetAddress(from));
message.addRecipient(
Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(
"Hello JavaMail Attachment");
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
messageBodyPart.setText("Hi");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
HTH
References:
JavaMail API – Sending Email Via Gmail SMTP Example
http://www.jguru.com/faq/view.jsp?EID=30251
I have an application that can send mails, implemented in Java. I want to put a HTML link inside de mail, but the link appears as normal letters, not as HTML link...
How can i do to inside the HTML link into a String? I need special characters? thank you so much
Update:
HI evereybody! thanks for oyu answers! Here is my code:
public static boolean sendMail(Properties props, String to, String from,
String password, String subject, String body)
{
try
{
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(mbp);
// Preparamos la sesion
Session session = Session.getDefaultInstance(props);
// Construimos el mensaje
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setContent(multipart);
message.addRecipient(
Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
// Lo enviamos.
Transport t = session.getTransport("smtp");
t.connect(from, password);
t.sendMessage(message, message.getAllRecipients());
// Cierre.
t.close();
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
And here the body String:
String link = "ACTIVAR CUENTA";
But in the received message the link appears as the link string, not as HTML hyperlink! I don't understand what happens...
Any solution?
Adding the link is as simple as adding the text inside the string. You should set your email to support html (it depends on the library you are using), and you should not escape your email content before sending it.
Update: since you are using java.mail, you should set the text this way:
message.setText(body, "UTF-8", "html");
html is the mime subtype (this will result in text/html). The default value that is used by the setText(string) method is plain
I'm just going to answer in case this didn't work for someone else.
I tried Bozho's method and for some reason the email wouldn't send when I did the setText on the message as a whole.
I tried
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html");
but this came as an attachment in Outlook instead of in the usual text. To fix this for me, and in Outlook, instead of doing the mbp.setContent and message.setText, I just did a single setText on the message body part. ie:
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(messageBody,"UTF-8", "html");
With my code for the message looking like this:
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
for(String str : to){
message.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
}
message.setSubject(subject);
// Create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(messageBody,"UTF-8","html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
Appending "http://" before the URL worked for me.
We can create html link in the email body by using java code.In my case I am developing reset password where I should create link and send to the user through the mail.you will create one string.With in a string you type all the url.If you add the http to the that .it behaves like link with in the mail.
Ex:String mailBody ="http://localhost:8080/Mail/verifytoken?token="+ token ;
you can send some value with url by adding query string.Her token has some encrypted value.
put mailBody in your mail body parameter.
ex": "Hi "+userdata.getFirstname()+
"\n\n You have requested for a new password from the X application. Please use the below Link to log in."+
"\n\n Click on Link: "+mailBody);
The above is the string that is parameter that you have to pass to your mail service.Email service takes parameters like from,to,subject,body.Here I have given body how it should be.you pass the from ,to,subject values according to your cast
you can do right way it is working for me.
public class SendEmail
{
public void getEmail(String to,String from, String userName,String password,Properties props,String subject,String messageBody)
{
MimeBodyPart mimeBodyPart=new MimeBodyPart();
mimeBodyPart.setContent(messageBody,"text/html");
MimeMultipart multipart=new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
Session session=Session.getInstance(props,new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(userName,password);
}
});
try{
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setContent(multipart);
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
message.setSubject("Have You got Mail!");
message.setText(messageBody,"UTF-8","html");
Transport.send(message);
}
catch(MessagingException ex){System.out.println(ex)}
public static void main(String arg[]){
SendEmail sendEmail=new SendEmail();
String to = "XXXXXXX#gmail.com";
String from = "XXXXXXXX#gmail.com";
final String username = "XXXXX#gmail.com";
final String password = "XXXX";
String subject="Html Template";
String body = "<i> Congratulations!</i><br>";
body += "<b>Your Email is working!</b><br>";
body += "<font color=red>Thank </font>";
String host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
sendEmail.getEmail(to,from,username,password,props,subject,body);
}
}