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.
Related
I am developing an app where I need to set image in a header and footer of a mail. I saw method setHeader(String header-name, String header_value) but when I put into it a path to my image I don't get anything.
This is my code:
public static void send(String host, String port,
final String userName, final String password, String toAddress,
String subject, String htmlBody,
Map<String, String> mapInlineImages)
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");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// 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.setHeader("image1", "D:\\broki\\src\\main\\resources\\imageHeader.jpg");
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlBody, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds inline image attachments
if (mapInlineImages != null && mapInlineImages.size() > 0) {
Set<String> setImageID = mapInlineImages.keySet();
for (String contentId : setImageID) {
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setHeader("Content-ID", "<" + contentId + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
String imageFilePath = mapInlineImages.get(contentId);
try {
imagePart.attachFile(imageFilePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(imagePart);
}
}
msg.setContent(multipart);
Transport.send(msg);
}
}
As you can see in part
msg.setHeader("image1", "D:\\broki\\src\\main\\resources\\imageHeader.jpg")
I put some key and value which is path to my Image which I want to set into header. But nothing happens. Can someone help me?
The word "header" in a MIME message refers to a section of the message that has "key: value" fields. This section is called "header" because it's transmitted before the "body" content of the message. The headers are for things like "Date", "Subject", "Content-Type".
The word "header" does not refer to a graphical header that would be visible on the screen or when printed. To add this type of a header, you have to modify the content of the message. In your program, that's stored in the htmlBody variable.
I don't think you can simply modify htmlBody to add a header to it, without knowing how it is structured. In the general case, the page header has to be incorporated in the HTML message design from the start.
So I have the problem with the Javamail where if I send an attachment in the mail the body disappears. When I don't send an attachment with the mail i can just see the body.
My GMailSender.java:
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");
session = Session.getDefaultInstance(props, this);
_multipart = new MimeMultipart();
}
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.setText(body);
message.setDataHandler(handler);
if(_multipart.getCount() > 0)
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);
}
public void addAttachment(String filename) throws Exception
{
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
My MainActivity.java
Button bt_send = findViewById(R.id.Alert);
bt_send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
BackgroundMail bm = new BackgroundMail(context);
bm.setGmailUserName("***#gmail.com");
bm.setGmailPassword("******");
bm.setMailTo(to);
bm.setFormSubject(value + " DOC/" + mTvResult.getText().toString());
bm.setFormBody("Document Nummer:\n" + mTvResult.getText().toString() + "\n \nDocument Type:\n" + value);
if (images.size() > 0) {
for (Object file : images) {
bm.setAttachment(file.toString());
}
}
bm.setSendingMessage("Loading...");
bm.setSendingMessageSuccess("The mail has been sent successfully.");
bm.send();
}
});
So how can i add an attachment while still being able to see the body itself?
Thanks in advance!
It looks like you copied GMailSender from someone else. You should start by fixing all these common mistakes.
You never call the addAttachment method. (Note that you could replace that method with the MimeBodyPart.attachFile method). Please remember to post the code that you're actually using.
The key insight that you're missing is that for a multipart message the main body part needs to be the first body part in the multipart. Your call to Message.setContent(_multipart); overwrites the message content that was set by your call to message.setDataHandler(handler);, which also overwrote the content set by your call to message.setText(body);.
Instead of setting that content on the message, you need to create another MimeBodyPart, set the content on that MimeBodyPart, and then add that MimeBodyPart as the first part of the multipart.
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 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".
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Some body please tell me about how to attach available pdf file to mail.
I am use mail.jar and activation.jar for sending a mail.
I can send mail but I dont know how to send pdf file with attachment.
so please suggest me about that
thank you.
I just try
String filename = "file.pdf";
Multipart multipart1 = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart1.addBodyPart(messageBodyPart);
But still it not get data, it empty attached.
Send E-Mail with Attachment using JavaMail :
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
class SendAttachment
{
public static void main(String [] args)
{
String to="ABC#gmail.com";//change accordingly
final String user="ABC#XYZ.com";//change accordingly
final String password="xxxxx";//change accordingly
//1) get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "mail.javatpoint.com");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password); } });
//2) compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Message Aleart");
//3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "SendAttachment.java";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart );
//7) send message
Transport.send(message);
System.out.println("message sent....");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
source: http://www.javatpoint.com/example-of-sending-attachment-with-email-using-java-mail-api
Try this:
String SMTP_HOST_NAME = "mail.domain.com";
String SMTP_PORT = "111";
String SMTP_FROM_ADDRESS="xxx#domain.com";
String SMTP_TO_ADDRESS="yyy#domain.com";
String subject="Textmsg";
String fileAttachment = "C:\\filename.pdf";
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT );
Session session = Session.getInstance(props,new javax.mail.Authenticator()
{protected javax.mail.PasswordAuthentication
getPasswordAuthentication()
{return new javax.mail.PasswordAuthentication("xxxx#domain.com","password");}});
try{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(SMTP_FROM_ADDRESS));
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
messageBodyPart.setText("Test mail one");
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
msg.setContent(multipart);
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(SMTP_TO_ADDRESS));
msg.setSubject(subject);
// msg.setContent(content, "text/plain");
Transport.send(msg);
System.out.println("success....................................");
}
catch(Exception e){
e.printStackTrace();
}
Source: http://www.coderanch.com/t/586537/java/java/sample-code-java-mail-api
You should create MimeMultipart, MimeBodyPart, FileDataSource and DataHandler as follows:
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String filePath = "<file system path>";
String fileName = "display name"
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
Now, On MimeMessage use setContent method.