记录项目里面用到的几个给国外邮箱发邮件的代码

一些说明:

这几个都可以正常发邮件,但是免费的每天都会有限制,发多了就会黑名单。。。

最终选择了exchange付费的版本,每天可以发1万条邮件,也不是很贵,基础的32一个月的就可以了

 

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import com.sun.mail.smtp.SMTPTransport;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.BodyType;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import javax.mail.Session;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;

public class SendHtmlMail {

    public static void main(String[] args) {
        String to = "******@gmail.com";

        StringBuffer theMessage = new StringBuffer();
        theMessage.append("<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><title>Title</title></head><body>测试一哈</body></html>");
             
        sendMessageByExchange("***","***","Test",to,theMessage.toString());
        
    }
    
    //Exchange服务发送
    public static int sendMessageByExchange(String username, String password,String subject, String to,String bodyText){
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
        ExchangeCredentials credentials = new WebCredentials(username,password);
        service.setCredentials(credentials);
        
        try {
            service.setUrl(new URI("https://smtp.office365.com/EWS/exchange.asmx"));
            EmailMessage msg = new EmailMessage(service);
            msg.setSubject(subject);
            MessageBody body = MessageBody.getMessageBodyFromText(bodyText);
            body.setBodyType(BodyType.HTML);
            msg.setBody(body);
            msg.getToRecipients().add(to);
            
            msg.send();
            return 1;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    //MG服务发送
    public static int sendMessageByMG(String from, String password, String to, String content, 
        String sender,String title) throws UnsupportedEncodingException{
        
        try {
            Properties props = System.getProperties();
            props.put("mail.smtps.host", "smtp.mailgun.org");
            props.put("mail.smtps.auth", "true");

            Session session = Session.getInstance(props, null);
            Message msg = new MimeMessage(session);
            
            msg.setFrom(new InternetAddress(from));
            
            InternetAddress[] addrs = InternetAddress.parse(to, false);
            msg.setRecipients(Message.RecipientType.TO, addrs);
            msg.setSubject(MimeUtility.encodeText(title, "gb2312", "B"));
            msg.setSentDate(new Date());
            msg.setContent(content, "text/html;charset=gb2312");

            SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
            t.connect("smtp.mailgun.org", from, password);
            t.sendMessage(msg, msg.getAllRecipients());

            System.out.println("To: " + to + "Response: " + t.getLastServerResponse());
            t.close();
            return 1;
        } catch (AddressException e) {
            e.printStackTrace();
            return 0;
        } catch (MessagingException e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    //outlook服务发送
    public static int sendMessageByOutLook(String from, String password, String to, String content, String sender,
        String title) throws MessagingException, java.io.UnsupportedEncodingException {

        try {
            Properties props = new Properties();
            // 开启debug调试
            props.setProperty("mail.debug", "true"); // false
            // 发送服务器需要身份验证
            props.setProperty("mail.smtp.auth", "true");
            // 设置邮件服务器主机名
            props.setProperty("mail.host", "smtp.office365.com");
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.port", "587");
            props.put("mail.smtp.starttls.enable", "true");

            // 设置环境信息
            Session session = Session.getInstance(props);
            InternetAddress toAddress = new InternetAddress(to);
            
            // 创建邮件对象
            MimeMessage testMessage = new MimeMessage(session);
            testMessage.setFrom(new InternetAddress(from,sender));
            testMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
            testMessage.setSentDate(new java.util.Date());
            testMessage.setSubject(MimeUtility.encodeText(title, "gb2312", "B"));

            testMessage.setContent(content, "text/html;charset=gb2312");

            Transport transport = session.getTransport();
            // 连接邮件服务器
            transport.connect(from, password);
            // 发送邮件
            transport.sendMessage(testMessage, testMessage.getAllRecipients());
            // 关闭连接
            transport.close();
            System.out.println("Message sent to " + to + " success!");
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //gmail服务发送
    public static int sendMessageByGmail(String from, String password, String to, String content, String sender, String title)
        throws MessagingException, java.io.UnsupportedEncodingException {

        try {
            // Step 1: Configure the mail session
            String host = "smtp.gmail.com";
            String port = "465";

            System.out.println("Configuring mail session for: " + host);
            java.util.Properties props = new java.util.Properties();
            props.setProperty("mail.smtp.auth", "true");// 指定是否需要SMTP验证
            props.put("mail.transport.protocol", "smtp");

            props.put("mail.smtp.user", from);
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.debug", "true");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", port);
            props.put("mail.smtp.timeout", "5000");
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");

            Session mailSession = Session.getDefaultInstance(props);
            mailSession.setDebug(false);// 是否在控制台显示debug信息

            // Step 2: Construct the message
            System.out.println("Constructing message -  from=" + from + "  to=" + to);
            InternetAddress fromAddress = new InternetAddress(from, sender);
            InternetAddress toAddress = new InternetAddress(to);

            MimeMessage testMessage = new MimeMessage(mailSession);
            testMessage.setFrom(fromAddress);
            testMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
            testMessage.setSentDate(new java.util.Date());
            testMessage.setSubject(MimeUtility.encodeText(title, "gb2312", "B"));

            testMessage.setContent(content, "text/html;charset=gb2312");
            System.out.println("Message constructed");

            // Step 3: Now send the message
            Transport transport = mailSession.getTransport("smtps");
            transport.connect(host, Integer.valueOf(port), from, password);
            transport.sendMessage(testMessage, testMessage.getAllRecipients());
            transport.close();

            System.out.println("Message sent to " + to + " success!");
            return 1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return 0;
        }
    }

}

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值