📄 sendmailthread.java
字号:
package com.sixtwenty;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.sql.*;
/**
* To send an email via a thread
*/
public class SendMailThread extends Thread {
/**
* The server's host
*/
protected String _serverHost;
/**
* The user's login to connect to the smtp server
*/
protected String _userLogin;
/**
* The password to connect to the smtp server
*/
protected String _password;
/**
* The author of the email
*/
protected String _from;
/**
* The email's subject
*/
protected String _subject;
/**
* The email's content
*/
protected String _content;
/**
* List of email to send
*/
protected String[] _emails;
/**
* The constructor of the SendMailThread Class
* @param serverHost The server's host
* @param userLogin The user's login to connect to the smtp server
* @param password The password to connect to the smtp server
* @param from The recipient of the email
*/
public SendMailThread(String serverHost, String userLogin, String password, String from) {
_serverHost = serverHost;
_userLogin = userLogin;
_password = password;
_from = from;
}
/**
* The method to send an email to a list of email addresses
* @param subject The email's subject
* @param content The email's content
* @param emails The email addresses to send this email
*/
public void send(String subject, String content, String[] emails) throws Exception {
_subject = subject;
_content = content;
_emails = emails;
// Launch the sending in a thread
start();
}
/**
* Send the emails in a thread
*/
public void run() {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", _serverHost);
props.setProperty("mail.user", _userLogin);
props.setProperty("mail.password", _password);
try {
Session mailSession = Session.getDefaultInstance(props, null);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(_subject);
message.setContent(_content, "text/plain");
// set the from and to address
InternetAddress addressFrom = new InternetAddress(_from);
message.setFrom(addressFrom);
// We send the email to all the email addresses in "emails"
for (int i=0; i < _emails.length; i++) {
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(_emails[i]));
}
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch(Exception e) {}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -