第1步:设置JavaMail环境
起首,我们须要下载包括javax.mail中一切类的jar文件。从oracle官方网站下载jar(mail.jar)文件。
现在在体系环境中设置类途径。Windows用户确保为Java装置设置了PATH变量。
Windows:
c:> set classpath=mail.jar;.;
Linux:
# export JAVA_HOME=/opt/jdk1.8.0_05/ # export PATH=$PATH:$JAVA_HOME/bin # export CLASSPATH=$JAVA_HOME/jre/lib/ext:$JAVA_HOME/lib/tools.jar:mail.jar:.
第2步:编写一个发送电子邮件的Java顺序
运用以下内容建立一个Java文件sEndoJavaApI.java。在此剧本中,须要依据请求将电子邮件从变量更改成变量。
import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMailJavaAPI { public static void main(String[] args) throws Exception{ String to="recipient@example.com"; String from="sender@example.com"; Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); String msgBody = "Sending email using JavaMail API..."; try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from, "NoReply")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to, "Mr. Recipient")); msg.setSubject("Welcome To Java Mail API"); msg.setText(msgBody); Transport.send(msg); System.out.println("Email sent successfully..."); } catch (AddressException e) { throw new RuntimeException(e); } catch (MessagingException e) { throw new RuntimeException(e); } } }
第3步:实行顺序以发送电子邮件
末了,我们须要实行Java顺序来发送电子邮件。正如我们所知,这发生在两个STPE中,第一个是编译顺序,第二个是运转顺序。
# javac SendMailJavaAPI.java # java SendMailJavaAPI
本篇文章到这里就已悉数完毕了,更多其他精彩内容能够关注ki4网的其他相干栏目教程!!!
以上就是JavaMail API—运用Java从当地SMTP发送电子邮件的细致内容,更多请关注ki4网别的相干文章!