欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java发送带附件的邮件,java附件邮件,package cn.o

来源: javaer 分享于  点击 39326 次 点评:216

java发送带附件的邮件,java附件邮件,package cn.o


package cn.outofmemory.snippets.enterprise;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import java.util.Date;import java.util.Properties;public class EmailAttachmentExample {    public static void main(String[] args) {        EmailAttachmentExample example = new EmailAttachmentDemo();        example.sendEmail();    }    public void sendEmail() {        // Strings that contain from, to, subject, body and file path to the attachment        String from = "sender@javacodegeeks.com";        String to = "receiver@javacodegeeks.com";        String subject = "Test mail";        String body = "Test body";        String filename = "C:\\sample.txt";        // Set smtp properties        Properties properties = new Properties();        properties.put("mail.smtp.host", "smtp.javacodegeeks.com");        properties.put("mail.smtp.port", "25");        Session session = Session.getDefaultInstance(properties, null);        try {            MimeMessage message = new MimeMessage(session);            message.setFrom(new InternetAddress(from));            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));            message.setSubject(subject);            message.setSentDate(new Date());            // Set the email body            MimeBodyPart messagePart = new MimeBodyPart();            messagePart.setText(body);            // Set the email attachment file            MimeBodyPart attachmentPart = new MimeBodyPart();            FileDataSource fileDataSource = new FileDataSource(filename) {                @Override                public String getContentType() {                    return "application/octet-stream";                }            };            attachmentPart.setDataHandler(new DataHandler(fileDataSource));            attachmentPart.setFileName(fileDataSource.getName());            // Add all parts of the email to Multipart object            Multipart multipart = new MimeMultipart();            multipart.addBodyPart(messagePart);            multipart.addBodyPart(attachmentPart);            message.setContent(multipart);            // Send email            Transport.send(message);        } catch (MessagingException e) {            e.printStackTrace();        }    }}
相关栏目:

用户点评