Sending email from Java
Clearly there are tutorials on the web that already describe how to programmatically send an email from a Java program, but the point of this blog is to post personal learnings and put them in some personal context, so I'll proceed thank you.
At my job now, I use Java for tasks for which previously I would have used perl or php. Part of the reason is to conform with the way the company uses Java more, and part is to learn and expand my Java knowledge. If time constraints were a big issue, I'd go with perl or php as both development and execution are faster in these languages. On to the implementation...
In the Java code, the System property for the SMTP host is set. Next, several actions are taken using the objects from the JavaMail library. To use these, the javax.mail.jar file may have to be downloaded and made available in the classpath for the program. A Session is created and a MimeMessage is created from the session. The "from", "to", subject, and body of the message are set, and then the Transport class is used to send the message. The "to" and "from" values are objects of type InternetAddress. Session, MimeMessage, InternetAddress, and Transport all are part of the JavaMail library.
In my experience, no email client has to be running on the computer for the email to be sent (as was necessary with a VB script I wrote recently), so the program really has few dependencies. Setting the SMTP host seems to be the key. Note: I won't actually post code here as a Google search will return examples, and most probably follow the steps described above.
At my job now, I use Java for tasks for which previously I would have used perl or php. Part of the reason is to conform with the way the company uses Java more, and part is to learn and expand my Java knowledge. If time constraints were a big issue, I'd go with perl or php as both development and execution are faster in these languages. On to the implementation...
In the Java code, the System property for the SMTP host is set. Next, several actions are taken using the objects from the JavaMail library. To use these, the javax.mail.jar file may have to be downloaded and made available in the classpath for the program. A Session is created and a MimeMessage is created from the session. The "from", "to", subject, and body of the message are set, and then the Transport class is used to send the message. The "to" and "from" values are objects of type InternetAddress. Session, MimeMessage, InternetAddress, and Transport all are part of the JavaMail library.
In my experience, no email client has to be running on the computer for the email to be sent (as was necessary with a VB script I wrote recently), so the program really has few dependencies. Setting the SMTP host seems to be the key. Note: I won't actually post code here as a Google search will return examples, and most probably follow the steps described above.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home