Created
September 26, 2010 02:05
-
-
Save mohamedmansour/597504 to your computer and use it in GitHub Desktop.
Send an email in Java
This file contains 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
// Email message | |
String toAddress = "someone@example.com"; | |
String fromAddress = "hello@mohamedmansour.com"; | |
String subject = "Hello Yahoo!" | |
String message = "From Java!"; | |
// Auth. | |
String host = "smtp.mail.yahoo.com"; | |
String port = "465"; | |
String username = "foo"; | |
String password = "bar"; | |
// Configure your JavaMail. | |
Properties props = new Properties(); | |
props.setProperty("mail.transport.protocol", "smtps"); | |
props.setProperty("mail.smtps.auth", "true"); | |
props.setProperty("mail.host", host); | |
props.setProperty("mail.port", port); | |
props.setProperty("mail.user", username); | |
props.setProperty("mail.password", password); | |
// Start an email session. | |
Session session = Session.getDefaultInstance(props, null); | |
Transport transport = session.getTransport("smtp"); | |
MimeMessage mimeMessage = new MimeMessage(session); | |
Multipart multiPart = new MimeMultipart(); | |
mimeMessage.setSubject(subject); | |
mimeMessage.addRecipient(RecipientType.TO, new InternetAddress(toAddress)); | |
MimeBodyPart textBodyPart = new MimeBodyPart(); | |
textBodyPart.setContent(message, "text/plain"); | |
multiPart.addBodyPart(textBodyPart); | |
mimeMessage.setContent(multiPart); | |
mimeMessage.setFrom(new InternetAddress(fromAddress)); | |
// Send email. | |
transport.connect(); | |
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); | |
transport.close(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment