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 SendMail { public static void main(String[] args) { String sendTo = "xxxxxxxx@gmail.com"; final String sentBy = "yyyyyyyy@gmail.com"; final String pwd = "*********";//Your Password Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", "587"); Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(sentBy, pwd); } }); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(sentBy)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress( sendTo)); msg.setSubject("Mail with attachment"); BodyPart bodyPart = new MimeBodyPart(); String text = "Hi User\n"; text += "This is the JAVA code to send Mail with attachment.\n"; text = text + "Regards,"; text = text + "Decoderr"; bodyPart.setText(text); MimeBodyPart attachmentPart = new MimeBodyPart(); String fileToAttach = "D:\\Mail.java"; DataSource source = new FileDataSource(fileToAttach); attachmentPart.setDataHandler(new DataHandler(source)); attachmentPart.setFileName(fileToAttach); Multipart _multipart = new MimeMultipart(); _multipart.addBodyPart(bodyPart); _multipart.addBodyPart(attachmentPart); msg.setContent(_multipart); Transport.send(msg); System.out.println("!!Mail sent!!"); } catch (MessagingException ex) { ex.printStackTrace(); } } }
0 comments :
Post a Comment