Created
August 23, 2020 18:51
-
-
Save jitunayak/0423abfbc141c2856535c272287144a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.util.Properties; | |
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 SendEmail { | |
public static void main(String[] args) { | |
//authentication info | |
final String username = "[email protected]"; | |
final String password = "password"; | |
String fromEmail = "[email protected]"; | |
String toEmail = "[email protected]"; | |
Properties properties = new Properties(); | |
properties.put("mail.smtp.auth", "true"); | |
properties.put("mail.smtp.starttls.enable", "true"); | |
properties.put("mail.smtp.host", "smtp.mail.yahoo.com"); | |
properties.put("mail.smtp.port", "587"); | |
Session session = Session.getInstance(properties, new javax.mail.Authenticator() { | |
protected PasswordAuthentication getPasswordAuthentication() { | |
return new PasswordAuthentication(username,password); | |
} | |
}); | |
//Start our mail message | |
MimeMessage msg = new MimeMessage(session); | |
try { | |
msg.setFrom(new InternetAddress(fromEmail)); | |
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); | |
msg.setSubject("Subject Line"); | |
Multipart emailContent = new MimeMultipart(); | |
//Text body part | |
MimeBodyPart textBodyPart = new MimeBodyPart(); | |
textBodyPart.setText("My multipart text"); | |
//Attachment body part. | |
MimeBodyPart pdfAttachment = new MimeBodyPart(); | |
pdfAttachment.attachFile("/home/parallels/Documents/docs/javamail.pdf"); | |
//Attach body parts | |
emailContent.addBodyPart(textBodyPart); | |
emailContent.addBodyPart(pdfAttachment); | |
//Attach multipart to message | |
msg.setContent(emailContent); | |
Transport.send(msg); | |
System.out.println("Sent message"); | |
} catch (MessagingException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment