How to send a pdf via e-mail from Java - java

How do I submit a pdf file to a generic e-mail from Java application?

You can Send E-Mail with PDF file as Attachment using reference of this -
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
class SendMailWithAttachment
{
public static void main(String [] args)
{
String to="XYZ#abc.com"; //Email address of the recipient
final String user="ABC#XYZ.com"; //Email address of sender
final String password="xxxxx"; //Password of the sender's email
//Get the session object
Properties properties = System.getProperties();
//Here pass your smtp server url
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); } });
//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");
//Create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
//Create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "YourPDFFileName.pdf";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//Create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//Set the multiplart object to the message object
message.setContent(multipart );
//Send message
Transport.send(message);
System.out.println("message sent....");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
You can also refer to JavaTPoint

delete the part :
//Here pass your smtp server url
properties.setProperty("mail.smtp.host",
"mail.javatpoint.com");
properties.put("mail.smtp.auth", "true");
And paste the code below :
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.socketFactory", "587");
props.put("mail.smtp.port", "587"); //587
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");

Related

Add title in send mail inside from.as like "Stack Overflow <do-not-reply#stackoverflow.email>"

I am not able to send mail to adding titles with from tab.
I need to add the title and text with the mail as like "Stack Overflow <do-not-reply#stackoverflow.email>"
How I will add the Stack Overflow title font of mail id.
My code is adding bellow
String to = "rabin.samanta#xxx.com";
String from = "rabin.samanta#xxx.com";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp-mail.outlook.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
String msgBody = "test............";
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from, "NoReply"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to, "Mr. Recipient"));
msg.setSubject("Welcome To Java Mail API");
msg.setText(msgBody);
msg.setHeader("header_name", "header_value");
Transport.send(msg);
System.out.println("Email sent successfully...");
}
You can simply use String from = "Rabin Samanta <rabin.samanta#xxx.com>";
From the InternetAddress class documentation
This class represents an Internet email address using the syntax of RFC822. Typical address syntax is of the form "user#host.domain" or "Personal Name <user#host.domain>".
https://docs.oracle.com/javaee/6/api/index.html?javax/mail/internet/InternetAddress.html
What happens when you try this
public static void main(String... args) throws Exception {
Properties props = new Properties();
props.put("mail.debug", "true");
props.put("mail.smtp.host", "mail.smtpbucket.com");
props.put("mail.smtp.port", "8025");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.auth", "false");
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setJavaMailProperties(props);
MimeMessage msg1 = javaMailSender.createMimeMessage();
MimeMessageHelper msg = new MimeMessageHelper(msg1, true);
String from= "Me <me#example.com>";
msg.setFrom(new InternetAddress(from));
msg.setTo("Me <me#example.com>");
msg.setText("Hello");
javaMailSender.send(msg1);
}
And check the SMTP Bucket https://www.smtpbucket.com/emails?sender=me#example.com

JavaMail Messaging Exception

I wrote a program to send gmails using JavaMail API. Following is my code:
import java.util.*;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;
import javax.mail.Session;
import javax.mail.Transport;
class emailSend{
public static void main(String[] args) {
String recipient = "receiver#gmail.com";
String sender = "sender#gmail.com";
String host = "smtp.gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.user", sender);
props.put("mail.smtp.password", "password");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
try
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
message.setSubject("This is the subject");
message.setText("This the message");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com",465,"sender01#gmail.com", "password");
transport.sendMessage(message, message.getAllRecipients());
System.out.println("Mail successfully sent");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
But I'm getting following error:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2197)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at emailSend.main(emailSend.java:29)
I tried disabling the firewall, but it was of no use.
What should I do?
Add properties:
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.ssl.checkserveridentity", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.debug", "true");
props.put("mail.smtp.EnableSSL.enable", "true");
props.put("mail.smtp.socketFactory.fallback", "false");
You need to configure your Gmail account security to allow it to send emails from your app check the link
This is my working code
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
//get Session
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( from, password);
}
});
//compose message
try {
MimeMessage message = new MimeMessage(session);
message.addRecipient(Message.RecipientType.TO,new InternetAddress(recepient));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(msg, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException e) {throw new RuntimeException(e);}

Send a table inside of RTF message JavaMail

I'm trying to send a email with a Table in string with RTF, but when I check the email the message body, the table lost the format, so I wondering what I'm doing wrong, this is the following chunk of code to send and email
public static void send(String asunto, String texto, String emailDestinatario){
final String username = "myemail#gmail.com";
final String password = "mypass";
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(username));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse( emailDestinatario));
message.setSubject(asunto);
message.setText(texto);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
what others configurations I need to send and email and recogniz me the format of table?
This is a document example to send via email
I get something like that(the table lost the format)
TARIFAS EMPLEADOS
TARIFA
IVA
TOTAL
EMPLEADOS HASTA $150.000.000
94,000
15,040
109,040
EMPLEADOS MAYOR DE $150.000.000
160,000
25,600
185,600
Have you tried something like :
MimeMessage message = new MimeMessage(sesion);
.
.
.
//Config your message....
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("RTF HTML TEXT", "text/html");
mp.addBodyPart(htmlPart);
message.setContent(mp);
Transport.send(message);

how to attach generated pdf file mail in java [closed]

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.

JavaMail - Task ends without errors but no mail is sent

recently i've been working on an automatic daily mail sender plus a weekly mail inside two different threads on my project.
The mail server is a MS Exchange (don't remember the version)
When the only daily mail was running, my mails were sent just fine.
Now that i've added another thread for the Weekly mails i have some of these issues:
Only one of the threads are able to send the email ( never both )
None of the threads are able to send email
On my logs i don't have evidence of errors, it seems the connection to the smtp server is not the problem and that the mail has been sent, but when i check my mailbox, no mails at all are arrived.
I'll post you the code about my Email class
public class Email {
boolean debug = false ;
String smtpServer = null;
int smtpPort = null;
String smtpSender = null;
String smtpUser = null;
String smtpPassword = null;
public Email(){
smtpServer = Config.SMTP_SERVER;
smtpPort = Config.SMTP_PORT;
smtpSender = Config.SMTP_SENDER;
smtpUser = Config.SMTP_USER;
smtpPassword = Config.SMTP_PASSWORD;
}
public void postMailAttach( String recipients[], String subject, String message, String filename ) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, null);
//SET SERVER FOR MESSAGE
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(smtpSender));
InternetAddress[] toAddress = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++){
toAddress[i] = new InternetAddress(recipients[i]);
}
//SET RECIPIENTS FOR MESSAGE
msg.setRecipients(Message.RecipientType.TO, toAddress);
//SET SUBJECT
msg.setSubject(subject);
//SET BODY PART OF MESSAGE
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(message);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
//GET FILES TO ATTACH
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
//SET FILE NAME
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
//SEND THE EMAIL
Transport transport = session.getTransport("smtp");
transport.connect(smtpServer,smtpPort,smtpUser,smtpPassword);
transport.sendMessage(msg,msg.getAllRecipients());
transport.close();
}
public void postMail (String recipients[], String subject, String message) throws MessagingException{
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
//session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(smtpSender);
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);
// Optional : You can also set your custom headers in the Email if you Want
//msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport transport = session.getTransport("smtp");
transport.connect(smtpServer,smtpPort,smtpUser,smtpPassword);
transport.sendMessage(msg,msg.getAllRecipients());
transport.close();
}
Thank you in advice for any suggestion.
After initializating properties like username, password etc
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);
}
});
hope this would help

Categories