深圳Java学习:Java发送邮件
使用Java应用程序发送 E-mail 十分简单,但是首先你应该在你的机器上安装 JavaMail API和Java Activation Framework (JAF) 。
1.发送一封简单的 E-mail
import java.util.;
import javax.mail.;
import javax.mail.internet.;
import javax.activation.;
public class SendEmail
{
public static void main(String[] args)
{
// 收件人电子邮箱
String to = “abcd@gmail.com”;
// 发件人电子邮箱
String from = “web@gmail.com”;
// 指定发送邮件的主机为 localhost
String host = “localhost”;
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty(“mail.smtp.host”, host);
Session session = Session.getDefaultInstance(properties);
try
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new
InternetAddress(to));
message.setSubject(“This is the Subject Line!”);
message.setText(“This is actual message”);
Transport.send(message);
System.out.println(“Sent message successfully…”);
}
catch(MessagingException mex)
{
mex.printStackTrace();
}
}
}
2.发送一封 HTML E-mail
import java.util.;
import javax.mail.;
import javax.mail.internet.;
import javax.activation.;
public class SendHTMLEmail
{
public static void main(String[] args)
{
// 收件人电子邮箱
String to = “abcd@gmail.com”;
// 发件人电子邮箱
String from = “web@gmail.com”;
// 指定发送邮件的主机为 localhost
String host = “localhost”;
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty(“mail.smtp.host”, host);
// 获取默认的 Session 对象。
Session session = Session.getDefaultInstance(properties);
try
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new
InternetAddress(to));
message.setSubject(“This is the Subject Line!”);
message.setContent(“
This is actual message
”, “text/html”);Transport.send(message);
System.out.println(“Sent message successfully…”);
}
catch(MessagingException mex)
{
mex.printStackTrace();
}
}
}