基本上我希望我的代码发送带附件的电子邮件(在本例中为epub)。
现在我使用sendgrid库发送邮件并将附件发送到sendgrid,它需要是base64编码并通过post发送到sendgrid服务器。
但是由于json不支持字节类型,我必须将我的编码文件转换为字符串。我试了很长时间,但不知道我做错了什么,但我相当肯定它与base64编码的字符串有关。
我的代码atm看起来像这样:
#Encoding file
with open(filename, 'rb') as f:
encoded = base64.b64encode(f.read())
attachment = Attachment()
#Is this done correctly?
attachment.content = str(encoded)
attachment.type = "application/epub+zip"
attachment.filename = filename
email = Mail(from_email, subject, to_email, content)
email.add_attachment(attachment)
response = sg.client.mail.send.post(request_body=email.get())
有人可以帮忙吗?
答案 0 :(得分:1)
使用Python 3时,发送电子邮件的文档似乎不起作用。我也遇到了这个问题。然后我找到了这个例子here
替换此行
attachment.content = encoded.decode()
同
public final class RconClient implements AutoCloseable {
private static final int MAX_SIZE = 4096;
private final Socket socket;
private final RconData data;
private static final Logger LOG = LoggerFactory.getLogger(RconClient.class);
@SuppressWarnings("ConstructorShouldNotThrowExceptions")
public RconClient(final String host,
final int port,
final byte[] password) throws IOException {
this.socket = new Socket(host, port);
final RconData requst = request(new RconData(RconData.AUTH, password));
if (requst.getId() == -1) {
LOG.error("Wrong password or ip to connect to rcon");
throw new LoginException(host, port);
}
this.data = read();
}
public String command(String command) throws IOException {
command = "get5_status";
final RconData response = request(new RconData(command.getBytes()));
return new String(response.getPayload(), Charset.forName("UTF-8"));
}
public RconData request(RconData packet) throws IOException {
try {
write(packet);
return read();
} catch (final SocketException exception) {
socket.close();
throw exception;
}
}
private void write(RconData packet) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(packet.getPayload().length + 14);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(packet.getPayload().length + 10);
buffer.putInt(packet.getId());
buffer.putInt(packet.getType());
buffer.put(packet.getPayload());
buffer.put((byte)0);
buffer.put((byte)0);
socket.getOutputStream().write(buffer.array());
socket.getOutputStream().flush();
}
private RconData read() throws IOException {
byte[] packet = new byte[MAX_SIZE];
int packetSize = this.socket.getInputStream().read(packet);
ByteBuffer buffer = ByteBuffer.wrap(packet, 0, packetSize);
buffer.order(ByteOrder.LITTLE_ENDIAN);
if (buffer.remaining() < 4) {
throw new WrongPacketException();
}
int size = buffer.getInt();
if (buffer.remaining() < size) {
throw new WrongPacketException();
}
int id = buffer.getInt();
int type = buffer.getInt();
byte[] payload = new byte[size - 10];
buffer.get(payload);
buffer.get(new byte[2]);
return new RconData(id, type, payload);
}
@Override
public void close() throws IOException {
this.socket.close();
}
}