使用此代码从 java 发送电子邮件,只需通过在按钮或您要发送电子邮件的任何其他位置传递所需参数来调用此类的构造函数。
import java.io.BufferedReader;
import java.io.InputStreamReader;
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 GMailSender {
public GMailSender(String host, final String from, final String pass, String to, String sub, String mess) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
// props.put("mail.smtp.port", port);
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}};
Session session = Session.getInstance(props, auth);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(sub);
message.setText(mess);
Transport.send(message);
}
public static void main(String arg[]) throws Exception {
if(arg.length == 5) {
StringBuilder message = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp = "", subject;
System.out.print("Enter subject: ");
subject = br.readLine();
System.out.println("Enter the message (end it with a . on a single line):");
while((temp = br.readLine()) != null) {
if(temp.equals("."))
break;
message.append(temp+"\n");
}
System.out.println("Sending message...");
new GMailSender(arg[0], arg[1], arg[2], arg[3], subject, message.toString());
System.out.println("Sent the message.");
}
else System.err.println("Usage:\njava SendTextMail <host> <port> <from> <pass> <to>");
}
}