📄 mailhelper.java
字号:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.util.Date;
public final class MailHelper {
public static void sendMsg(
String strHost,
int nPort,
String strUserName,
String strPassWord,
String strFrom,
String strToList,
String strCCList,
String strBCCList,
String strSubject,
String strMessage)
throws Exception {
// create some properties and get the default Session
Properties props = new Properties();
props.put("mail.smtp.host", strHost);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
//create a message
Message msg = new MimeMessage(session);
//from
InternetAddress from = new InternetAddress(strFrom);
msg.setFrom(from);
//to
if (strToList != null && strToList.length() > 0) {
InternetAddress[] to = { new InternetAddress(strToList)};
msg.setRecipients(Message.RecipientType.TO, to);
} else {
throw new Exception("No Recipient");
}
//cc
if (strCCList != null && strCCList.length() > 0) {
InternetAddress[] cc = { new InternetAddress(strCCList)};
msg.setRecipients(Message.RecipientType.CC, cc);
}
//bcc
if (strBCCList != null && strBCCList.length() > 0) {
InternetAddress[] bcc = { new InternetAddress(strBCCList)};
msg.setRecipients(Message.RecipientType.BCC, bcc);
}
//subject
if (strSubject != null) {
msg.setSubject(strSubject);
}
//sent date
msg.setSentDate(new Date());
//message
if (strMessage != null && strMessage.trim().length() > 0) {
msg.setText(strMessage);
} else
msg.setText("No message to be sent!");
msg.saveChanges();
//send the message
int nMailPort = -1;
if (nPort > 0)
nMailPort = nPort;
Transport transport = session.getTransport("smtp");
transport.connect(strHost, nMailPort, strUserName, strPassWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
public static void main(String[] args) {
try {
MailHelper.sendMsg(
"smtp.163.net",
0,
"shizhiguo",
"szg(8271)",
"shizhiguo@163.net",
"shizhiguo@tom.com",
"",
"",
"Hello World!",
"This is a test!");
} catch (AuthenticationFailedException ae) {
ae.printStackTrace();
} catch (SendFailedException sf) {
Address[] invalid = sf.getInvalidAddresses();
Address[] valid = sf.getValidSentAddresses();
Address[] unsend = sf.getValidUnsentAddresses();
sf.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -