【问题标题】:Setting sender's name in Java while sending email using Gmail使用 Gmail 发送电子邮件时在 Java 中设置发件人姓名
【发布时间】:2015-04-12 00:15:55
【问题描述】:

我从“快速入门:发送 Gmail”中复制了代码,并对我的应用进行了一些修改。代码似乎运行良好,只是无论我如何尝试都没有设置发件人的姓名。

这是我的完整代码:

import java.util.Arrays;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;

public class Test{
	private static final String SCOPE = "https://www.googleapis.com/auth/gmail.modify";
	private static final String APP_NAME = "XYZ";
	// Path to the client_secret.json file deloper Console
	private static final String CLIENT_SECRET_PATH = "src/testapp/auth_client.json";

	private static GoogleClientSecrets clientSecrets;
	private static GoogleAuthorizationCodeFlow flow;
	private static HttpTransport httpTransport;
	private static JsonFactory jsonFactory;
	private static Gmail service;

	public static String getRequestUrl() throws FileNotFoundException, IOException{
		httpTransport = new NetHttpTransport();
		jsonFactory = new JacksonFactory();
		
		clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(
				CLIENT_SECRET_PATH));
		
		// Allow user to authorize via url.
		flow = new GoogleAuthorizationCodeFlow.Builder(
				httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
		.setAccessType("online").setApprovalPrompt("auto").build();
		
		String url = flow.newAuthorizationUrl()
				.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build();
		
		return url;
	}
	
	public static void sendMail(String to, String sub, String body) throws IOException, MessagingException {

		Message message = createMessageWithEmail(createEmail(to, "me", sub, body));
	    message = service.users().messages().send("me", message).execute();
	    
	    System.out.println("Message id: " + message.getId());
	    System.out.println(message.toPrettyString());
	}

	static void emailCredentialSetup(String code) throws IOException {
		// Generate Credential using retrieved code.
		GoogleTokenResponse response = flow.newTokenRequest(code)
				.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
				.execute();
		GoogleCredential credential = new GoogleCredential()
				.setFromTokenResponse(response);

		// Create a new authorized Gmail API client
		service = new Gmail.Builder(httpTransport, jsonFactory,
				credential).setApplicationName(APP_NAME).build();
	}
	
	/**
	   * Create a MimeMessage using the parameters provided.
	   *
	   * @param to Email address of the receiver.
	   * @param from Email address of the sender, the mailbox account.
	   * @param subject Subject of the email.
	   * @param bodyText Body text of the email.
	   * @return MimeMessage to be used to send email.
	   * @throws MessagingException
	 * @throws UnsupportedEncodingException 
	   */
	  private static MimeMessage createEmail(String to, String from, String subject,
	      String bodyText) throws MessagingException, UnsupportedEncodingException {
	    Properties props = new Properties();
	    Session session = Session.getDefaultInstance(props, null);

	    MimeMessage email = new MimeMessage(session);

	    email.setFrom(new InternetAddress(from, "SPecial message"));
	    email.addRecipient(javax.mail.Message.RecipientType.TO,
	                       new InternetAddress(to));
	    email.setSubject(subject);
	    email.setText(bodyText);
	    return email;
	  }
	  
	  /**
	   * Create a Message from an email
	   *
	   * @param email Email to be set to raw of message
	   * @return Message containing base64 encoded email.
	   * @throws IOException
	   * @throws MessagingException
	   */
	  private static Message createMessageWithEmail(MimeMessage email)
	      throws MessagingException, IOException {
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    email.writeTo(baos);
	    String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
	    Message message = new Message();
	    message.setRaw(encodedEmail);
	    return message;
	  }
	  
	public static void main(String[] args) throws FileNotFoundException, IOException, MessagingException {
		System.out.println(getRequestUrl());
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		emailCredentialSetup(br.readLine());
		
		sendMail("myemail@gmail.com", "TEST1", "Hello");
	}
}

有人可以帮我将发件人姓名设置为自定义字符串吗?经过一番谷歌搜索后,我尝试将名称设置为“特殊消息”,但它不起作用。

【问题讨论】:

    标签: java email oauth-2.0 google-api gmail-api


    【解决方案1】:

    看起来你正在做的代码:

      email.setFrom(new InternetAddress("me", "SPecial message"));
    

    它试图在电子邮件标题中使用“我”作为电子邮件地址,这是行不通的。您需要将其设置为用户的真实电子邮件地址,或者只是不提供 From 标头以使其自动设置。 (如果 From 标头中的电子邮件地址对用户来说是错误的,它会删除整个标头并设置一个有效的标头。)

    【讨论】:

    • 感谢@Eric DeFriez 的回答。我现在想用授权的用户名替换“我”。既然,我不是直接从用户那里得到它,你建议我如何获取它?
    • 为什么不完全避免使用 From 标头?如果未提供,Gmail API 将为用户设置默认值,这可能是您想要的。
    • 您对@Eric DeFrez 的要求是正确的,但是完全删除 From 标头不会让默认标头出现。我评论了“email.setFrom(new InternetAddress(from, "SPecial message"));”上面代码中的行并显示默认名称。
    • 嗯,我很困惑“但是完全删除 From 标头不会让默认的标头出现”与“我评论了 [From 标头设置代码] ...并且默认名称正在获取显示”。是哪个?
    • 很抱歉打错了 Eric。我的意思是“......并且默认名称没有显示”
    【解决方案2】:

    从你的名字“Special Message”中删除空格尝试以“SpecialMessage”的方式发送它应该可以。

    【讨论】:

    • 我想你必须在这里做一些大的改变,检查下面的 url:developers.google.com/admin-sdk/email-settings/… 检查 Java 选项卡...你需要更改 send-as 别名...
    • 为什么要链接到 Admin SDK 电子邮件迁移 API?这段代码显然使用了 Gmail API。
    猜你喜欢
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2018-01-20
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多