使用JavaMail发送邮件
时间:2010-12-13 csdn博客 沈斌
代码如下:
package demo;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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;
import sun.misc.BASE64Encoder;
public class MailSender ...{
public static void main(String[] args) ...{
MailSender sender = new MailSender();
sender.setHost("smtp.sina.com.cn");
sender.setFromAddr("");
sender.setToAddr("");
sender.setUsername("wwwwwwww");
sender.setPassword("ssssssss");
sender.setTitle("关于提高效率的几点想法");
sender.setAttachPath("C:singleUser.sql");
sender.setAttachName("singleUser.sql");
try ...{
sender.sendMail();
} catch (Exception e) ...{
e.printStackTrace();
}
}
public void sendMail() throws Exception...{
Properties props = new Properties();
props.put("mail.smtp.host", getHost());
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(getFromAddr()));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(getToAddr()));
message.setSubject(getTitle());
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
contentPart.setText("邮件的具体内容在此");
multipart. addBodyPart(contentPart);
if(getAttachPath() != null && getAttachName() != null)...{
BodyPart attachmentPart= new MimeBodyPart();
DataSource source = new FileDataSource(getAttachPath ());
attachmentPart.setDataHandler(new DataHandler(source));
BASE64Encoder enc = new BASE64Encoder();
attachmentPart.setFileName("=?GBK?B? "+enc.encode(getAttachName().getBytes())+"?=");
multipart.addBodyPart(attachmentPart);
}
message.setContent(multipart);
message.saveChanges();
Transport transport = session.getTransport ("smtp");
transport.connect(host, getUsername(), getPassword());
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
private String host = null;
private String fromAddr = null;
private String toAddr = null;
private String username = null;
private String password = null;
priva
|