项目学习主题一:java mail

 
 

需要的jar包 jmail.jar ,activation.jar;

import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;



public class JavaMail {


private String host = "";
private String user = "";
private String pwd ="";
private String from = "";
private String to = "";
private String subject = "";



public void setAddress(String to, String subject) {
this.to = to;
this.subject = subject;
}



public void send(String txt) {
Properties props = new Properties();
props.put("mail.smtp.host", host);


props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);


session.setDebug(true);


MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.setSubject(subject);
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
contentPart.setText(txt);
multipart.addBodyPart(contentPart);
message.setContent(multipart);
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, user, pwd);
MailcapCommandMap mc = (MailcapCommandMap) CommandMap
.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}


}
}



public  class Test{
public  static void main(String args[]){
JavaMail javaMail = new JavaMail();
javaMail.setAddress(strMail, strTempMailMessage);
javaMail.send(strTempMailMessage);
}
}



你可能感兴趣的:(项目学习主题一:java mail)