我们如何使用我的Java(Android Studio)应用程序的AWS发送SMTP电子邮件

发布于 2025-01-31 01:46:01 字数 1927 浏览 1 评论 0 原文

我怀疑这是我的transport.connect(host,smtp_username,smtp_password);线。我认为根本没有建立联系。我的代码目前看起来像这样:

private void sendEmail(String messegeToSend) {

    final String FROM = "[email protected]";
    final String FROMNAME = "Joe Blogs";
    final String TO = "[email protected]";
    final String HOST = "email-smtp.us-west-2.amazonaws.com";
    final int PORT = 587;
    final String SMTP_USERNAME = "smtpusername";
    final String SMTP_PASSWORD = "smtppassword";

    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(FROM));
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(TO));
        message.setSubject("InvoiceRequest");
        message.setText(messegeToSend);
        Transport transport = session.getTransport();

        transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);

        Toast.makeText(getApplicationContext(),"Connected!",Toast.LENGTH_LONG).show();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

    }catch (MessagingException e){
        Toast.makeText(getApplicationContext(),"Sorry, We ran into a problem"+ e.getMessage(),Toast.LENGTH_LONG).show();
        throw  new RuntimeException(e);
    }
}

最后,我想最终从此应用程序中发送一封电子邮件。我以前在使用Google的Gmail SMTP,但要退役,因此我已切换到 AWS SES,我现在正在努力。

I suspect it is my transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD); line. I think there is no connection established at all. My code currently looks like this:

private void sendEmail(String messegeToSend) {

    final String FROM = "[email protected]";
    final String FROMNAME = "Joe Blogs";
    final String TO = "[email protected]";
    final String HOST = "email-smtp.us-west-2.amazonaws.com";
    final int PORT = 587;
    final String SMTP_USERNAME = "smtpusername";
    final String SMTP_PASSWORD = "smtppassword";

    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(FROM));
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(TO));
        message.setSubject("InvoiceRequest");
        message.setText(messegeToSend);
        Transport transport = session.getTransport();

        transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);

        Toast.makeText(getApplicationContext(),"Connected!",Toast.LENGTH_LONG).show();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

    }catch (MessagingException e){
        Toast.makeText(getApplicationContext(),"Sorry, We ran into a problem"+ e.getMessage(),Toast.LENGTH_LONG).show();
        throw  new RuntimeException(e);
    }
}

At the end of it all, I want to finally send an email from within this app. I was previously using Google's Gmail SMTP but it is to be decommissioned, hence I have switched to
AWS SES, which I am now struggling with.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼趣 2025-02-07 01:46:01

经历了您也遇到的同样的问题。

网络操作,例如transport.connect(),也必须在线程中运行!在主线程上提出网络请求将导致线程等待或阻止。因此,解决方案的问题是将AmazonSessame类扩展到线程类。

步骤1)我假设您已经遵循Amazon AWS文档上提供的步骤,以通过Amazon SES SES SMTP接口编程发送电子邮件。如果不是这样的话,则是它的链接:

步骤2)如果您尚未这样做,请下载并导入以下JAR文件:


步骤3)将以下实现添加到您的build.gradle文件:

dependencies{
implementation files('libs\\javax.mail.jar')
implementation files('libs\\javax.activation.jar')
implementation files('libs\\javax.additionnal.jar')
}

步骤4)而不是遵循它们提供的代码,这是修改版本工作:

import android.os.Build;

import androidx.annotation.RequiresApi;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@RequiresApi(api = Build.VERSION_CODES.O)
public class AmazonSESSample extends Thread{

    // Replace [email protected] with your "From" address.
    // This address must be verified.
    static final String FROM = "[email protected]";
    static final String FROMNAME = "Sender Name";
    
    // Replace [email protected] with a "To" address. If your account 
    // is still in the sandbox, this address must be verified.
    static final String TO = "[email protected]";
    
    // Replace smtp_username with your Amazon SES SMTP user name.
    static final String SMTP_USERNAME = "smtp_username";
    
    // Replace smtp_password with your Amazon SES SMTP password.
    static final String SMTP_PASSWORD = "smtp_password";
    
    // The name of the Configuration Set to use for this message.
    // If you comment out or remove this variable, you will also need to
    // comment out or remove the header below.
    static final String CONFIGSET = "ConfigSet";
    
    // Amazon SES SMTP host name. This example uses the US West (Oregon) region.
    // See https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html#region-endpoints
    // for more information.
    static final String HOST = "email-smtp.us-west-2.amazonaws.com";
    
    // The port you will connect to on the Amazon SES SMTP endpoint. 
    static final int PORT = 587;
    
    static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)";
    
    static final String BODY = String.join(
            System.getProperty("line.separator"),
            "<h1>Amazon SES SMTP Email Test</h1>",
            "<p>This email was sent with Amazon SES using the ", 
            "<a href='https://github.com/javaee/javamail'>Javamail Package</a>",
            " for <a href='https://www.java.com'>Java</a>."
        );

    public void run() {

        // Create a Properties object to contain connection configuration information.
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", PORT); 
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");

        // Create a Session object to represent a mail session with the specified properties. 
        Session session = Session.getDefaultInstance(props);

        // Create a message with the specified information. 
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(FROM,FROMNAME));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        msg.setSubject(SUBJECT);
        msg.setContent(BODY,"text/html");
        
        // Add a configuration set header. Comment or delete the 
        // next line if you are not using a configuration set
        msg.setHeader("X-SES-CONFIGURATION-SET", CONFIGSET);
            
        // Create a transport.
        Transport transport = session.getTransport();
                    
        // Send the message.
        try
        {
            System.out.println("Sending...");
            
            // Connect to Amazon SES using the SMTP username and password you specified above.
            transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);
            
            // Send the email.
            transport.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Email sent!");
        }
        catch (Exception ex) {
            System.out.println("The email was not sent.");
            System.out.println("Error message: " + ex.getMessage());
        }
        finally
        {
            // Close and terminate the connection.
            transport.close();
        }
    }
}

也必须将以下JAR库导入到项目中很重要:

  1. javax.activation.jar
  2. javax.additionnal.jar
  3. javax.mail.jar.jar

Experienced the same exact problem you had too.

Networking operations, like transport.connect(), have to be ran in Threads too! Making a network request on the main thread will cause the thread to wait, or block. Thus, the problem to your solution would be to extend the AmazonSESSample class to the Thread class.

Step 1) I am assuming that you have followed the steps provided on Amazon's AWS documentation to send emails programmatically through Amazon SES SMTP interface. If not here is the link to it: here.

Step 2) Download and import the following jar files if you have yet to do so:

https://drive.google.com/drive/folders/1q5n2ROQvlmvkW7DAWyhGxzceRustouhK?usp=sharing

Step 3) Add the following implementations to your build.gradle file:

dependencies{
implementation files('libs\\javax.mail.jar')
implementation files('libs\\javax.activation.jar')
implementation files('libs\\javax.additionnal.jar')
}

Step 4) Instead of following the code they provided, this is the modified version that worked:

import android.os.Build;

import androidx.annotation.RequiresApi;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@RequiresApi(api = Build.VERSION_CODES.O)
public class AmazonSESSample extends Thread{

    // Replace [email protected] with your "From" address.
    // This address must be verified.
    static final String FROM = "[email protected]";
    static final String FROMNAME = "Sender Name";
    
    // Replace [email protected] with a "To" address. If your account 
    // is still in the sandbox, this address must be verified.
    static final String TO = "[email protected]";
    
    // Replace smtp_username with your Amazon SES SMTP user name.
    static final String SMTP_USERNAME = "smtp_username";
    
    // Replace smtp_password with your Amazon SES SMTP password.
    static final String SMTP_PASSWORD = "smtp_password";
    
    // The name of the Configuration Set to use for this message.
    // If you comment out or remove this variable, you will also need to
    // comment out or remove the header below.
    static final String CONFIGSET = "ConfigSet";
    
    // Amazon SES SMTP host name. This example uses the US West (Oregon) region.
    // See https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html#region-endpoints
    // for more information.
    static final String HOST = "email-smtp.us-west-2.amazonaws.com";
    
    // The port you will connect to on the Amazon SES SMTP endpoint. 
    static final int PORT = 587;
    
    static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)";
    
    static final String BODY = String.join(
            System.getProperty("line.separator"),
            "<h1>Amazon SES SMTP Email Test</h1>",
            "<p>This email was sent with Amazon SES using the ", 
            "<a href='https://github.com/javaee/javamail'>Javamail Package</a>",
            " for <a href='https://www.java.com'>Java</a>."
        );

    public void run() {

        // Create a Properties object to contain connection configuration information.
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", PORT); 
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");

        // Create a Session object to represent a mail session with the specified properties. 
        Session session = Session.getDefaultInstance(props);

        // Create a message with the specified information. 
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(FROM,FROMNAME));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        msg.setSubject(SUBJECT);
        msg.setContent(BODY,"text/html");
        
        // Add a configuration set header. Comment or delete the 
        // next line if you are not using a configuration set
        msg.setHeader("X-SES-CONFIGURATION-SET", CONFIGSET);
            
        // Create a transport.
        Transport transport = session.getTransport();
                    
        // Send the message.
        try
        {
            System.out.println("Sending...");
            
            // Connect to Amazon SES using the SMTP username and password you specified above.
            transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);
            
            // Send the email.
            transport.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Email sent!");
        }
        catch (Exception ex) {
            System.out.println("The email was not sent.");
            System.out.println("Error message: " + ex.getMessage());
        }
        finally
        {
            // Close and terminate the connection.
            transport.close();
        }
    }
}

It is important that you have imported the following jar libraries into your project too:

  1. javax.activation.jar
  2. javax.additionnal.jar
  3. javax.mail.jar
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文