sendapp.java
来自「Struts2 + Spring JPA Hibernate demo.」· Java 代码 · 共 80 行
JAVA
80 行
package com.vegeta.utils;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendApp {
public static void send(String smtpServer, String to, String from, String subject, String body) {
try {
// java.security.Security.addProvider(new
// com.sun.net.ssl.internal.ssl.Provider());
Properties props = System.getProperties();
// -- Attaching to default Session, or we could start a new one --
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
final String login = "thinhbv";
final String pwd = "tinhban195";
Authenticator pa = null; // default: no authentication
if (login != null && pwd != null) { // authentication required?
props.put("mail.smtp.auth", "true");
pa = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, pwd);
}
};
}// else: no authentication
Session session = Session.getInstance(props, pa);
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
// -- Set the subject and body text --
msg.setSubject(subject);
msg.setText(body);
// -- Set some other header information --
msg.setHeader("X-Mailer", "LOTONtechEmail");
msg.setSentDate(new Date());
msg.saveChanges();
// -- Send the message --
Transport.send(msg);
System.out.println("Message sent OK.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Main method to send a message given on the command line.
*/
public static void main(String[] args) {
{
try {
String smtpServer = "smtp.gmail.com";
String to = "cadic195@gmail.com";
String from = "thinhbv@gmail.com";
String subject = "Hello from Java";
String body = "Test using java to send mail.";
send(smtpServer, to, from, subject, body);
System.out.println("Finish!");
} catch (Exception ex) {
System.out.println("Usage: ");
}
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?