Java Mail Interview Questions and Answers
Question: Sample code for java mail api with attachment.Answer: String SMTP_HOST_NAME = "mail.domain.com";String SMTP_PORT = "25"; 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(); } |
Is it helpful?
Yes
No
Most helpful rated by users:
- What is JavaMail?
- Explain POP, SMTP and IMAP protocols.
- Discuss about JavaMail.
- Explain the structure of Javamail API
- What are the advantages of JavaMail?