The process for sending mail with attachment involves a session object,
MineBody, MultiPart objects. Here the mind-body is used to set the text
message and it is carried by MultiPart object. The following is the code.
package firstmail;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public
class
sendingattachments {
public
static
void
main(String[] args) {
String to =
"abc@gmail.com"
;
String from =
"abc@gmail.com"
;
"
;
final String username =
"abc@gmail.com"
;
"
;
final String password =
"12345"
;
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"
);
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(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(
"sendinngattachments.java"
);
BodyPart messageBodyPart =
new
MimeBodyPart();
messageBodyPart.setText(
"hey u, follwong is the message find it."
);
Multipart multipart =
new
MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart =
new
MimeBodyPart();
String filename =
"E:/xyz-CV.PDF"
;
DataSource source =
new
FileDataSource(filename);
messageBodyPart.setDataHandler(
new
DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println(
"Sent message successfully...."
);
}
catch
(MessagingException e) {
throw
new
RuntimeException(e);
}
}
}
No comments:
Post a Comment