使用javamail进行邮件发送

本文介绍如何使用JavaMail API进行邮件发送,包括引入必要的类、设置邮件内容、附件和SMTP服务器配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用javamail进行邮件发送

// 在javax.mail包中的类,需要引入的。
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.URLDataSource;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import javax.mail.*;

看看测试方法:

public static void main(String args[]) throws Exception {
        String strAttachmentFileName = "project.txt";
        String fileAttachment = "http://....../project.txt";

        String from = "from@mail.com.cn";
        String to = "to@mail.com.cn";

        Session session1;

        Properties properties1 = System.getProperties();

        properties1.setProperty("mail.transport.protocol", "smtp");
        properties1.setProperty("mail.smtp.auth", "true");
        properties1.setProperty("mail.smtp.host", "smtp.exmail.qq.com");

        session1 = Session.getInstance(properties1, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
            // 注册的可以发送的邮件账号
                return new PasswordAuthentication(
                        "postmaster@mail.com.cn","password");   
            }
        });

        // Define message
        MimeMessage message = new MimeMessage(session1);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("Hello JavaMail Attachment");

        Multipart multipart = new MimeMultipart();

        // create the message part
        MimeBodyPart messageBodyPart = new MimeBodyPart();

        // fill message
        messageBodyPart.setText(
            "<h2>Hello</h2><p>This is the content for this email.</p><p>中文内容测试</p>",
            "utf-8", "html");
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        // 如果有多个,多次操作添加atta
            MimeBodyPart messageBodyPart1 = new MimeBodyPart();

            URL fileURL = new URL(fileAttachment);
            DataSource source = new URLDataSource(fileURL);
            messageBodyPart1.setDataHandler(new DataHandler(source));
            messageBodyPart1.setFileName(strAttachmentFileName);
            multipart.addBodyPart(messageBodyPart1);

        // Put parts in message
        message.setContent(multipart);

        // Send the message
        Transport.send(message);
    }

稍后到邮箱检查,可以看到发送的邮件了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值