Maison> Java> javaDidacticiel> le corps du texte

JavaMail API—使用Java从本地SMTP发送电子邮件

不言
Libérer: 2019-03-15 10:51:46
original
3779 Les gens l'ont consulté

JavaMail API支持用于发送电子邮件的JavaMail(javax.mail)接口。javax.mail具有发送电子邮件和SMTP,POP3和IMAP等其他邮件协议所需的所有类。在本篇文章中,我们使用JavaMail API通过本地smtp服务器使用Java发送电子邮件。确保在localhost上运行smtp服务器。

JavaMail API—使用Java从本地SMTP发送电子邮件

第1步:设置JavaMail环境

首先,我们需要下载包含javax.mail中所有类的jar文件。从oracle官方网站下载jar(mail.jar)文件。

现在在系统环境中设置类路径。Windows用户确保为Java安装配置了PATH变量。

Windows:

c:> set classpath=mail.jar;.;
Copier après la connexion

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:.
Copier après la connexion

第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); } } }
Copier après la connexion

第3步:执行程序以发送电子邮件

最后,我们需要执行Java程序来发送电子邮件。正如我们所知,这发生在两个STPE中,第一个是编译程序,第二个是运行程序。

# javac SendMailJavaAPI.java # java SendMailJavaAPI
Copier après la connexion

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注php中文网的其他相关栏目教程!!!

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!