📄 sendmail.java
字号:
package org.redsoft.forum.mail;import org.redsoft.forum.util.Validation;import javax.mail.*;import javax.mail.internet.*;import java.util.*;/** * A simple util class that sends out emails * @author David Xu * @author Charles Huang * @version 1.1 */public class SendMail { /** * "send" method to send the message. * @param to To e-mail address. * @param from From e-mail address,optional.If not provided, will use "redsoft@chinaxp.org". * @param subject Subject of the mail * @param body Mail body * @exception Exception if to e-mail address is empty */ public static void send( final String to, final String from, final String subject, final String body ) throws javax.mail.MessagingException, javax.mail.internet.AddressException { //TODO: read the hardcoded values from propertiy file Validation.validateNotNull( to ); Validation.validateNotNull( from ); Validation.validateNotNull( subject ); Validation.validateNotNull( body ); //final String smtpServer="www.chinaxp.org"; final String smtpServer="127.0.0.1"; final String user = "chinaxp"; final String password = "3edc4rfv"; final Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); final Session session = Session.getDefaultInstance(props, null); session.setDebug(false); final Transport tr = session.getTransport("smtp"); tr.connect(smtpServer, user, password); MimeMessage msg = new MimeMessage( session ); final MimeBodyPart mbp1 = new MimeBodyPart(); final MimeMultipart mp = new MimeMultipart(); msg.setFrom( new InternetAddress(from) ); msg.setRecipient( Message.RecipientType.TO, new InternetAddress( to ) ); msg.setSubject( subject,"GB2312"); mbp1.setText(body, "GB2312"); mp.addBodyPart(mbp1); msg.setContent( mp ); msg.setSentDate(new java.util.Date()); msg.saveChanges(); // don't forget this Transport.send( msg ); tr.close(); } class XAuthenticator extends Authenticator{ private String user; private String password; public XAuthenticator( final String user, final String password ){ Validation.validateNotNull( user ); Validation.validateNotNull( password ); } public PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication( user, password ); } } public static void main( String[] args ){ try{ SendMail.send( "charles.huang@hp.com","charles@chinaxp.org","Notification","<html><img src='http://www.chinaxp.org/forum/images/logo.gif'><b>test</b></html>"); }catch( final Exception exception ){ exception.printStackTrace(); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -