如何使用 Java 发送电子邮件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/884943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:40:15  来源:igfitidea点击:

How do I send an e-mail in Java?

javaemailtomcatservlets

提问by Steve McLeod

I need to send e-mails from a servlet running within Tomcat. I'll always send to the same recipient with the same subject, but with different contents.

我需要从 Tomcat 中运行的 servlet 发送电子邮件。我将始终以相同的主题发送给同一收件人,但内容不同。

What's a simple, easy way to send an e-mail in Java?

用 Java 发送电子邮件的简单方法是什么?

Related:

有关的:

How do you send email from a Java app using GMail?

如何使用 GMail 从 Java 应用程序发送电子邮件?

采纳答案by RichieHindle

Here's my code for doing that:

这是我这样做的代码:

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

// Set up the SMTP server.
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", "smtp.myisp.com");
Session session = Session.getDefaultInstance(props, null);

// Construct the message
String to = "[email protected]";
String from = "[email protected]";
String subject = "Hello";
Message msg = new MimeMessage(session);
try {
    msg.setFrom(new InternetAddress(from));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(subject);
    msg.setText("Hi,\n\nHow are you?");

    // Send the message.
    Transport.send(msg);
} catch (MessagingException e) {
    // Error.
}

You can get the JavaMail libraries from Sun here: http://java.sun.com/products/javamail/

您可以在此处从 Sun 获取 JavaMail 库:http: //java.sun.com/products/javamail/

回答by Jherico

use the Java Mail library

使用 Java 邮件库

import javax.mail.*

...

Session mSession = Session.getDefaultInstance(new Properties());
Transport mTransport = null;
mTransport = mSession.getTransport("smtp");
mTransport.connect(cServer, cUser, cPass);
MimeMessage mMessage = new MimeMessage(mSession);
mTransport.sendMessage(mMessage,  mMessage.getAllRecipients());
mTransport.close();

This is a truncated version of the code I use to have an application send emails. Obviously, putting a body and recipients in the message before sending it is probably going to suit you better.

这是我用来让应用程序发送电子邮件的代码的截断版本。显然,在发送消息之前将正文和收件人放入消息中可能更适合您。

The maven repository location is artifactId: javax.mail, groupId: mail.

maven 存储库位置是 artifactId:javax.mail,groupId:mail。

回答by Jon

JavaMail can be a bit of a pain to use. If you want a simpler, cleaner, solution then have a look at the Spring wrapper for JavaMail. The reference docs are here:

JavaMail 使用起来可能有点麻烦。如果您想要一个更简单、更清晰的解决方案,那么请查看 JavaMail 的 Spring 包装器。参考文档在这里:

http://static.springframework.org/spring/docs/2.5.x/reference/mail.html

http://static.springframework.org/spring/docs/2.5.x/reference/mail.html

However, this does mean you need Spring in your application, if that isn't an option then you could look at another opensource wrapper such as simple-java-mail:

但是,这确实意味着您的应用程序中需要 Spring,如果这不是一个选项,那么您可以查看另一个开源包装器,例如 simple-java-mail:

simplejavamail.org

简单的javamail.org

Alternatively, you can use JavaMail directly, but the two solutions above are easier and cleaner ways to send email in Java.

或者,您可以直接使用 JavaMail,但上述两种解决方案是使用 Java 发送电子邮件的更简单、更简洁的方法。

回答by Steve K

Yet another option that wraps the Java Mail API is Apache's commons-email.

包装 Java Mail API 的另一个选项是Apache 的 commons-email

From their User Guide.

从他们的用户指南。

SimpleEmail email = new SimpleEmail();
email.setHostName("mail.myserver.com");
email.addTo("[email protected]", "John Doe");
email.setFrom("[email protected]", "Me");
email.setSubject("Test message");
email.setMsg("This is a simple test of commons-email");
email.send();

回答by Yishai

JavaMail is great if you can rely on an outside SMTP server. If, however, you have to be your own SMTP server, then take a look at Asprin.

如果您可以依赖外部 SMTP 服务器,则 JavaMail 非常有用。但是,如果您必须成为自己的 SMTP 服务器,那么请查看Asprin

回答by Maurice Perry

I usually define my javamail session in the GlobalNamingResources section of tomcat's server.xml file so that my code does not depend on the configuration parameters:

我通常在 tomcat 的 server.xml 文件的 GlobalNamingResources 部分定义我的 javamail 会话,以便我的代码不依赖于配置参数:

<GlobalNamingResources>
    <Resource name="mail/Mail" auth="Container" type="javax.mail.Session"
              mail.smtp.host="localhost"/>
    ...
</GlobalNamingResources>

and I get the session via JNDI:

我通过 JNDI 获取会话:

    Context context = new InitialContext();
    Session sess = (Session) context.lookup("java:comp/env/mail/Mail");

    MimeMessage message = new MimeMessage(sess);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject, "UTF-8");
    message.setText(content, "UTF-8");
    Transport.send(message);

回答by user109771

To followup on jon's reply, here's an example of sending a mail using simple-java-mail.

为了跟进 jon 的回复,这里有一个使用simple-java-mail发送邮件的例子。

The idea is that you don't need to know about all the technical (nested) parts that make up an email. In that sense it's a lot like Apache's commons-email, except that Simple Java Mail is a little bit more straightforward than Apache's mailing API when dealing with attachments and embedded images. Spring's mailing facility works as well but is a bit awkward in use (for example it requires an anonymous innerclass) and ofcourse you need to a dependency on Spring which gets you much more than just a simple mailing library, since it its base it was designed to be an IOC solution.

这个想法是您不需要了解构成电子邮件的所有技术(嵌套)部分。从这个意义上说,它很像 Apache 的 commons-email,只是在处理附件和嵌入图像时,Simple Java Mail 比 Apache 的邮件 API 更直接一些。Spring 的邮件工具也能工作,但使用起来有点尴尬(例如它需要一个匿名内部类),当然你需要依赖于 Spring,它不仅仅是一个简单的邮件库,因为它是它的基础设计成为国际奥委会的解决方案。

Simple Java Mail btw is a wrapper around the JavaMail API.

Simple Java Mail btw 是 JavaMail API 的包装器。

final Email email = new Email();

email.setFromAddress("lollypop", "[email protected]"); 
email.setSubject("hey");
email.addRecipient("C. Cane", "[email protected]", RecipientType.TO);
email.addRecipient("C. Bo", "[email protected]", RecipientType.BCC); 
email.setText("We should meet up! ;)"); 
email.setTextHTML("<img src='cid:wink1'><b>We should meet up!</b><img src='cid:wink2'>");

// embed images and include downloadable attachments 
email.addEmbeddedImage("wink1", imageByteArray, "image/png");
email.addEmbeddedImage("wink2", imageDatesource); 
email.addAttachment("invitation", pdfByteArray, "application/pdf");
email.addAttachment("dresscode", odfDatasource);

new Mailer("smtp.host.com", 25, "username", "password").sendMail(email);
// or alternatively, pass in your own traditional MailSession object.
new Mailer(preconfiguredMailSession).sendMail(email);

回答by SuperSaiyan

Here is the simple Solution

这是简单的解决方案

Download these jars: 1. Javamail 2. smtp 3. Java.mail

下载这些 jars: 1. Javamail 2. smtp 3. Java.mail

Copy and paste the below code from [http://javapapers.com/core-java/java-email/][1]

从以下位置复制并粘贴以下代码 [http://javapapers.com/core-java/java-email/][1]

Edit the ToEmail, Username and Password (Gmail User ID and Pwd)

编辑 ToEmail、用户名和密码(Gmail 用户 ID 和密码)

回答by srinivas gowda

Add java.mail jar into your class path if it is non maven project Add the below dependency into your pom.xml execute the code

如果它是非 maven 项目,则将 java.mail jar 添加到您的类路径中将以下依赖项添加到您的 pom.xml 中执行代码

 <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4</version>
    </dependency>

Below is the tested code

下面是经过测试的代码

import java.util.Date;
    import java.util.Properties;

    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;

    public class MailSendingDemo {
        static Properties properties = new Properties();
        static {
            properties.put("mail.smtp.host", "smtp.gmail.com");
            properties.put("mail.smtp.port", "587");
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.starttls.enable", "true");
        }
        public static void main(String[] args) {
            String returnStatement = null;
            try {
                Authenticator auth = new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("yourEmailId", "password");
                    }
                };
                Session session = Session.getInstance(properties, auth);
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress("yourEmailId"));            
                message.setRecipient(Message.RecipientType.TO, new InternetAddress("recepeientMailId"));
                message.setSentDate(new Date());
                message.setSubject("Test Mail");
                message.setText("Hi");
                returnStatement = "The e-mail was sent successfully";
                System.out.println(returnStatement);    
                Transport.send(message);
            } catch (Exception e) {
                returnStatement = "error in sending mail";
                e.printStackTrace();
            }
        }
    }

回答by Tarit Ray

Tested Code send Mail with attachment :

测试代码发送带有附件的邮件:

  public class SendMailNotificationWithAttachment {

            public static void mailToSendWithAttachment(String messageTosend, String snapShotFile) {

                String to = Constants.MailTo;
                String from = Constants.MailFrom;
                String host = Constants.smtpHost;// or IP address
                String subject = Constants.subject;
                // Get the session object
                Properties properties = System.getProperties();
                properties.setProperty("mail.smtp.host", host);
                Session session = Session.getDefaultInstance(properties);
                try {
                    MimeMessage message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(from));
                    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
                    message.setSubject(subject);
                    // message.setText(messageTosend);
                    BodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setText(messageTosend);
                    Multipart multipart = new MimeMultipart();
                    multipart.addBodyPart(messageBodyPart);

                    messageBodyPart = new MimeBodyPart();
                    String filepath = snapShotFile;

                    DataSource source = new FileDataSource(filepath);
                    messageBodyPart.setDataHandler(new DataHandler(source));

                    Path p = Paths.get(filepath);
                    String NameOffile = p.getFileName().toString();

                    messageBodyPart.setFileName(NameOffile);
                    multipart.addBodyPart(messageBodyPart);

                    // Send the complete message parts
                    message.setContent(multipart);

                    // Send message
                    Transport.send(message);

        //          Log.info("Message is sent Successfully");
        //          System.out.println("Message is sent Successfully");
                    System.out.println("Message is sent Successfully");
    } catch (MessagingException e) {
    //          Log.error("Mail sending is Failed " + "due to" + e);
                SendMailNotificationWithAttachment smnwa = new SendMailNotificationWithAttachment();
                smnwa.mailSendFailed(e);
                throw new RuntimeException(e);
            }
        }
public void mailSendFailed(MessagingException e) {
        System.out.println("Mail sending is Failed " + "due to" + e);
        Log log = new Log();
        log.writeIntoLog("Mail sending is Failed " + "due to" + e.toString(), false);
    }

}