使用 Java 发送 HTML 电子邮件

Posted

技术标签:

【中文标题】使用 Java 发送 HTML 电子邮件【英文标题】:Sending HTML email with Java 【发布时间】:2013-05-26 07:45:29 【问题描述】:

我似乎无法弄清楚如何使用 java 发送 html 电子邮件 :( :( 我阅读了教程并最终得到了以下代码:

Properties props = new Properties();

    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.socketFactory.port", SSLPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", SSLPort);

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() 
        protected PasswordAuthentication getPasswordAuthentication() 
            return new PasswordAuthentication(username, pass);
        
    );

    try 
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(baseEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTO));
        message.setSubject(emailSubject);
        message.setContent(schemeParsed, "text/html" ); //; charset=" + charset);
        message.setSentDate(new Date());
        Transport.send(message); 

发送消息。我测试过:

大标题

但相反,我收到了纯文本:
<html><body><h2>big caption</h2></body></html>

MIME 版本:1.0 内容类型:文本/html; charset=us-ascii 内容传输编码:7bit X-WP-AV: skaner antywirusowy poczty Wirtualnej Polski S. A. X-WP-SPAM: NO 0000000 [8ZJt]

以上内容是由我的电子邮件服务器添加的(不知何故)。而且……就是这样。不能让它工作。有什么帮助吗?

【问题讨论】:

【参考方案1】:

我遇到了同样的问题,但它实际上是一个非常简单的解决方法。你所要做的就是改变

message.setContent(schemeParsed, "text/html" ); //; charset=" + charset);

message.setText(schemeParsed, "utf-8", "html"); 

然后一切都应该工作。如果你认为你的变量可能有问题,这里是我的所有代码。

import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;

public class Drivers 

    static Scanner scanly = new Scanner(System.in);
    public static String username = "your-email@your-domain.com";
    public static String name = "";
    public static String password = "your-password";
    public static String recipient = "";
    public static String subject = "";
    public static String emessage = "";
    public static String answer = "";
    public static String count = "";
    public static String wait = "";
    public static boolean loop = true;
    public static int countint;
    public static int waitint;

    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException 

        print("Hi! Welcome! Please begin by entering the recipient: ");
        recipient = scanly.nextLine();
        print("What would you like your name to be?");
        name = scanly.nextLine();
        print("What would you like the subject line to be?");
        subject = scanly.nextLine();
        print("Please enter the message:");
        emessage = scanly.nextLine();

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.mail.yahoo.com");
        props.put("mail.smtp.port", "25");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() 
            protected PasswordAuthentication getPasswordAuthentication() 
                return new PasswordAuthentication(username, password);
            
          );

        print("Recipient: " + recipient + "\nSubject: " + subject + "\nMessage: " + emessage);

        while(loop)
        
            print("Type 's' to send the message, 'c' to cancel, 'n' to change the message/subject, or 'sp' to choose how many.");
            answer = scanly.nextLine(); 
            if(answer.toLowerCase().equals("s"))
            
                print("Establishing connection..");
                MimeMessage message = new MimeMessage(session);
                try 
                    print("Setting up defaults..");
                    message.setFrom(new InternetAddress(username, name));
                    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
                    message.setSubject(subject);
                    message.setText(emessage, "utf-8", "html"); 
                    print("Sending..");
                    Transport.send(message);
                 catch (MessagingException e) 
                    e.printStackTrace();
                

                print("Sent!");
                print("Pausing..");

             else if(answer.toLowerCase().equals("c")) 
            print("Bye!");
                System.exit(0);
             else if(answer.toLowerCase().equals("n")) 
                main(args);
             else if(answer.toLowerCase().equals("sp"))
            
                print("How many times?");
                count = scanly.nextLine();
                countint = Integer.parseInt(count);
                print("What would you like the wait time to be? (Recommended is 4000-10000)");
                wait = scanly.nextLine();
                waitint = Integer.parseInt(wait);
                for (int i = 0; i < countint; 
                
                    print("Establishing connection..");
                    Message message = new MimeMessage(session);
                    try 
                        print("Setting up defaults..");
                        message.setFrom(new InternetAddress(username, name));
                        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
                        message.setSubject(subject);
                        message.setText(emessage); 
                        print("Sending..");
                        Transport.send(message);
                     catch (MessagingException e) 
                        e.printStackTrace();
                    

                    print("Sent!");
                    Thread.sleep(waitint);
                
             else
            
                print("Error..");
            
        

    

    public static void print(String ttp)
    
        System.out.println(ttp);
    


无论如何,如果有任何问题或任何事情,请通过 drenagem-github@outlook.com 给我发电子邮件

【讨论】:

【参考方案2】:

这行得通吗?

MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setText(unescapeHtml(messageString));
multipart.addBodyPart(bodyPart);

这里,unescapeHtml(...) 是您选择的一些 unescape 方法,MimeBodyPartjavax.mail.internet.MimeBodyPart,我假设您已经在使用 javax.mail.internet.MimeMessage

【讨论】:

以上是关于使用 Java 发送 HTML 电子邮件的主要内容,如果未能解决你的问题,请参考以下文章

java使用smtp发送html格式邮件

java使用smtp发送html格式邮件

java使用smtp发送html格式邮件

Java发送邮件初窥

使用Java Mail发送邮件

对于从 java 程序发送的电子邮件,html 内容中的 png 图像未显示在 gmail 客户端上