java邮件发送

public boolean send(String to[], String cc[], String bcc[], String subject,
                     String content,String fileList[]) {
         String fileList1[] = new String[2];
        fileList1[0] = "D:\\1635405805(1).jpg";
        fileList1[1] = "D:\\word.docx";
        //这里是手动设置图片和文件作为附件测试
        try {
            Properties properties = new Properties(); // Properties p =

            // 发件人电子邮箱
            //final String from = new String(Base64Utils.decode(mailFrom), CharsetUtils.UTF_8);
            final String from = "12345678@163.com";

            // 发件人电子邮箱密码
            //final String pass = new String(Base64Utils.decode(mailPass), CharsetUtils.UTF_8);
            final String pass = "ABCDFGDGFDDSFSD"; //这个就麻烦点了,比如163的邮箱,找到设置-->POP3/SMTP/IMAP-->POP3/SMTP服务 已开启 就会有一个第三方登录的码复制过来即可

            // 设置邮件服务器
            //properties.setProperty("mail.smtp.host", mailHost); // 邮件服务器
            properties.setProperty("mail.smtp.host", "smtp.163.com"); // 邮件服务器


            properties.put("mail.smtp.auth", "true");
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            // 获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() { // qq邮箱服务器账户、第三方登录授权码
                    return new PasswordAuthentication(from, pass); // 发件人邮件用户名、密码
                }
            });

            Message message = new MimeMessage(session); // 建立信息
            BodyPart messageBodyPart = new MimeBodyPart();
            Multipart multipart = new MimeMultipart();
            message.setFrom(new InternetAddress(from)); // 发件人

            String toList, ccList, bccList;

            // 发送,
            if (null != to && to.length > 0) {
                toList = getMailList(to);
                InternetAddress[] iaToList = new InternetAddress().parse(toList);
                message.setRecipients(Message.RecipientType.TO, iaToList); // 收件人
            }

            // 抄送
            if (null != cc && cc.length > 0) {
                ccList = getMailList(cc);
                InternetAddress[] iaCcList = new InternetAddress().parse(ccList);
                message.setRecipients(Message.RecipientType.CC, iaCcList); // 抄送人
            }

            // 密送
            if (null != bcc && bcc.length >0) {
                bccList = getMailList(bcc);
                InternetAddress[] iaBccList = new InternetAddress().parse(bccList);
                message.setRecipients(Message.RecipientType.BCC, iaBccList); // 密送人
            }
            message.setSentDate(new Date()); // 发送日期
            message.setSubject(subject); // 主题
            message.setText(content); // 内容
            // 显示以html格式的文本内容
            messageBodyPart.setContent(content, "text/html;charset=utf-8");
            multipart.addBodyPart(messageBodyPart);

            // 2.保存多个附件
            if (null != fileList1 && fileList1.length > 0) {
                addTach(fileList1, multipart);
            }

            message.setContent(multipart);
            // 邮件服务器进行验证
            // 发送消息
            Transport.send(message);
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 添加多个附件
    public void addTach(String fileList[], Multipart multipart)
            throws MessagingException, UnsupportedEncodingException {
        for (int index = 0; index < fileList.length; index++) {
            MimeBodyPart mailArchieve = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(fileList[index]);
            mailArchieve.setDataHandler(new DataHandler(fds));
            String attacheFilename = MimeUtility.encodeText(fds.getName(), CharsetUtils.UTF_8, "B");
            mailArchieve.setFileName(attacheFilename);
            multipart.addBodyPart(mailArchieve);
        }
    }

    private String getMailList(String[] mailArray) {

        StringBuffer toList = new StringBuffer();
        int length = mailArray.length;
        if (mailArray != null && length < 2) {
            toList.append(mailArray[0]);
        } else {
            for (int i = 0; i < length; i++) {
                toList.append(mailArray[i]);
                if (i != (length - 1)) {
                    toList.append(",");
                }

            }
        }
        return toList.toString();

    }

转码类

package com.*.utils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.SystemUtils;
import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
import org.mozilla.intl.chardet.nsPSMDetector;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * 项目名称:RenRenERP <br />
 * 类名称:CharsetUtils <br />
 * 创建人:Administrator <br />
 * 备注: <br />
 * 
 * @version <br />
 */
public class CharsetUtils extends org.apache.http.util.CharsetUtils
{
	public static final String UTF_8 = "UTF-8";
	public static final String UTF_16 = "UTF-16BE";

	public static final String GBK = "GBK";
	public static final String GB2312 = "GB2312";

	public static final String ISO8859_1 = "ISO8859_1";

	public static final String WINDOWS_1252 = "windows-1252";
	public static final String UNICODE = "Unicode";

	private Charset charset = Charset.defaultCharset();
	private boolean found = false;

	private static boolean debug = false;

	/**
	 * 默认的输入流编码
	 */
	public static Charset defaultOutputCharset()
	{
		if (SystemUtils.IS_OS_WINDOWS)
			return debug ? Charset.forName(UTF_8) : Charset.forName(GB2312);
		else
			return Charset.forName(UTF_8);
	}

	/**
	 * 根据文件名获取文件的编码方式
	 */
	public Charset getCharset(String fileName)
	{
		InputStream inputStream = null;
		BufferedInputStream bufferedInputStream = null;

		try
		{
			inputStream = new FileInputStream(fileName);
			bufferedInputStream = new BufferedInputStream(inputStream);

			byte[] byteArray = new byte[1024];
			bufferedInputStream.read(byteArray);

			nsDetector detector = new nsDetector(nsPSMDetector.ALL); // 语言线索常量

			// Set an observer...
			// The Notify() will be called when a matching charset is found.
			detector.Init(new nsICharsetDetectionObserver()
			{
				public void Notify(String charsetName)
				{
					charset = Charset.forName(charsetName);
					found = true;
				}
			});

			detector.DoIt(byteArray, byteArray.length, false); // 测试
			detector.DataEnd(); // 测试结束!

			if (!found)
			{
				String probableCharsets[] = detector.getProbableCharsets();
				charset = Charset.forName(probableCharsets[0]);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			IOUtils.closeQuietly(bufferedInputStream);
			IOUtils.closeQuietly(inputStream);
		}

		return charset;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java邮件发送工具是JavaMail API。可以使用JavaMail API来发送文本邮件、HTML邮件、带附件的邮件等。 在Java中,可以使用MimeMessage类和MimeMessageHelper类来创建并发送邮件。首先,需要添加依赖项javax.mail到项目的pom.xml文件中: ``` <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> ``` 然后,可以使用以下代码来创建和发送邮件: ```java import javax.mail.*; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessageHelper; public class EmailSender { public static void sendEmail(String to, String subject, String content, String from) { // 创建Session对象 Session session = Session.getDefaultInstance(new Properties()); try { // 创建MimeMessage对象 MimeMessage message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress(from)); // 设置收件人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置主题 message.setSubject(subject); // 设置内容 message.setContent(content, "text/html"); // 发送邮件 Transport.send(message); System.out.println("邮件发送成功"); } catch (MessagingException e) { System.err.println("邮件发送失败"); } } } ``` 以上是一个简单的Java邮件发送工具类的示例。使用该工具类可以发送包含HTML代码的邮件。你可以调用`sendEmail`方法来发送邮件,其中`to`参数是收件人的邮箱地址,`subject`参数是邮件的主题,`content`参数是邮件的内容,`from`参数是发件人的邮箱地址。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值